javascript-objects - 这段代码有什么问题?我没有定义
问题描述
代码:
const john = { fullName: 'johny Rodes', mass: 92, height: 1.95, calcBMI: ()=>{ this.bmi = this.mass / this.height ** 2; return this.bmi; } };
john.calcBMI();
console.log(john.bmi);
解决方案
javascript中的箭头函数继承自该调用范围,因此在您的情况下this
实际上是指全局this
,而不是john
对象。
const john = {
fullName: 'johny Rodes',
mass: 92,
height: 1.95,
// calcBMI is an arrow function, so "this" is bound to the calling state
calcBMI: () => {
this.bmi = this.mass / this.height ** 2;
return this.bmi;
},
// "this" in calcBMI2 refers to this object
calcBMI2() {
this.bmi = this.mass / this.height ** 2;
return this.bmi;
},
};
由于mass
和height
不存在于调用范围内,箭头函数导致undefined
. 但是,常规函数继承了它所属类的范围。
john.calcBMI();
console.log(john.bmi); // => undefined
john.calcBMI2();
console.log(john.bmi); // => 24.194608809993426
如果你要在函数调用之外设置质量和高度,它现在可以工作了。
const this.mass = 92;
const this.height = 1.95;
// the "this" in the current scope is not the "john" object
john.calcBMI();
console.log(john.bmi); // => 24.194608809993426
请参阅涉及同一主题的这个问题
推荐阅读
- c# - 在 Selenium 测试中传递参数的正确位置?
- javascript - 在打印预览上重绘图形 - 不是函数(嵌套 Vue 组件)
- php - “未捕获的 Twig_Error_Loader”错误与 Materialise 模板,OpenCart 3
- python - 有条件的熊猫唯一值
- python - 在 Python 2.7 中,为什么字符串在文本模式下比在二进制模式下写得更快?
- spring - 使用 RestTemplae 获取 vavr Multimap 后的反序列化错误
- machine-learning - PyTorch 教程中的交叉熵计算
- excel - 更新图表的源数据范围
- git - 如果我从另一个分支推送,是否会在 git 分支上提交?
- ubuntu - Pylint 不能在 Jenkins 内部运行