Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The arrow function does not work when I put it inside the object, the result after call is NaN [duplicate]

Tags:

javascript

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?

like image 281
Dewa Prabawa Avatar asked Jan 27 '23 22:01

Dewa Prabawa


2 Answers

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
like image 77
Karim Avatar answered Feb 13 '23 02:02

Karim


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);
like image 35
Scath Avatar answered Feb 13 '23 02:02

Scath