首页 > 解决方案 > 这段代码有什么问题?我没有定义

问题描述

代码:

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-objects

解决方案


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; 
    },

}; 

由于massheight不存在于调用范围内,箭头函数导致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

请参阅涉及同一主题的这个问题


推荐阅读