var mySelf = {
name: "dina",
job: "Programmer",
yearOfBirth: 1993,
age: () => 2019 - this.yearOfBirth
};
let result = mySelf.age();
console.log(result);
the result is NaN
please help me what actually happened?
The arrow function inherit the enclosing context (that is Window
in this case) rather then the object context, use a plain function instead.
var mySelf = {
name: "dina",
job: "Programmer",
yearOfBirth: 1993,
age: function() { return 2019 - this.yearOfBirth }
};
let result = mySelf.age();
console.log(result);
To show that an arrow function receives a lexical this
-
const o =
{ func: () => this === window }
console.log(o.func()) // true
If use the name mySelf
instead of this
(because it will not reference the object in this case) to reference your object it seems to work fine.
var mySelf = {
name: "dina",
job: "Programmer",
yearOfBirth: 1993,
age: () => 2019 - mySelf.yearOfBirth
};
let result = mySelf.age();
console.log(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With