The reason it is returning NaN
when calling multi()
is because of the peculiarity of the this
keyword. The this
in the multi
function is not referring to the temp
object as you might expect but instead referring to the global this
. Run the following code to see the specific values being used in multi
:
let temp = {
a: 10,
b: 20,
sum() {
console.log('running `sum`:', 'this === window?', this === window);
console.log(this.a, this.b, this.a + this.b);
return this.a + this.b;
},
multi: () => {
console.log('running `multi`:', 'this === window?', this === window);
console.log(this.a, this.b, this.a * this.b);
return this.a * this.b;
}
};
console.log(temp.sum());
console.log(temp.multi());
In order to resolve it in multi
, call the properties of temp
instead of this
(or change the signature of multi to be multi() {
as sum
is):
let temp = {
a: 10,
b: 20,
sum() {
console.log('running `sum`:', 'this === window?', this === window);
console.log(this.a, this.b, this.a + this.b);
return this.a + this.b;
},
multi: () => {
console.log('running `multi`:', 'temp === window?', temp === window);
console.log(temp.a, temp.b, temp.a * temp.b);
return temp.a * temp.b;
}
};
console.log(temp.sum());
console.log(temp.multi());