Code:
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);
Code:
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);
Arrow functions in javascript inherit from that calling scope, so this
actually refers to the global this
in your case, not the john
object.
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;
},
};
As mass
and height
do not exist in the calling scope, the arrow function results in undefined
. However, the regular function inherits the scope of the class it belongs to.
john.calcBMI();
console.log(john.bmi); // => undefined
john.calcBMI2();
console.log(john.bmi); // => 24.194608809993426
If you were to set mass and height outside of the function call, it would now work.
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
See this question which touches on the same subject