0 javascript ecmascript-6 arrow-functions
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
Run Code Online (Sandbox Code Playgroud)
我不明白为什么 Javascript 对象中的箭头函数似乎不起作用。如果您查看上面的代码,第一个 console.log 将打印 NaN,第二个 console.log 将按预期打印数字。
从文档中:
箭头函数表达式的语法比函数表达式更短,并且不绑定自己的this、arguments、super或 new.target。这些函数表达式最适合非方法函数,并且不能用作构造函数。
你必须使用旧的方式,就像你已经展示的那样
area: function() {
return this.width*this.height;
}
Run Code Online (Sandbox Code Playgroud)
如果你仍然想使用箭头函数,你必须调用对象本身
area: function() {
return this.width*this.height;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1370 次 |
| 最近记录: |