Javascript 对象中的箭头函数

Arrow function in Javascript Object

let objNewWay = {
  width:400,
  height:300,
  area: () => this.width*this.height
};

console.log(objNewWay.area()); // NaN

let objOldWay = {
  width:400,
  height:300,
  area: function() {
    return this.width*this.height;
  }
};

console.log(objOldWay.area()); // 120000

我不明白为什么 Javascript 对象中的箭头函数似乎不起作用。如果您查看上面的代码,第一个 console.log 打印 NaN,第二个按预期打印数字。

https://jsbin.com/pazazikayi/edit?js,console

来自documentation :

An arrow function expression has a shorter syntax than a function expression and does not bind its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.

你必须像你已经展示的那样使用旧方法

area: function() {
   return this.width*this.height;
}

如果你还想使用箭头函数,你必须调用对象本身

let objNewWay = {
  width:400,
  height:300,
  area: ()=> objNewWay.width*objNewWay.height
};

console.log(objNewWay.area()); // NaN

arrow functions 不是 lambda,您使用它的方式将引用与您的对象不同的范围。

例如,从控制台:

let theObj = {
    whereAmI: () => console.log(this)
}

theObj.whereAmI();

// Window...

如果要使用 this 关键字,请使用 area: function(){} 方式。