This question already has answers here:
Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?

(3 个回答)


2年前关闭。



var mySelf = {
  name: "dina",
  job: "Programmer",
  yearOfBirth: 1993,
  age: () => 2019 - this.yearOfBirth
};

let result = mySelf.age();

console.log(result);

结果是 NaN
请帮我看看到底发生了什么?

最佳答案

如果使用名称 mySelf 而不是 this (因为在这种情况下它不会引用对象)来引用您的对象,它似乎工作正常。

var mySelf = {
  name: "dina",
  job: "Programmer",
  yearOfBirth: 1993,
  age: () => 2019 - mySelf.yearOfBirth
};

let result = mySelf.age();

console.log(result);

关于javascript - 箭头函数放在对象里面时不起作用,调用后的结果是NaN,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54113841/

10-12 06:44