Javascript对象中的Arrow函数
我不明白为什么Javascript对象中的箭头函数似乎不起作用。如果查看上面的代码,第一个console.log将打印NaN,第二个将按预期打印数字 来自: 箭头函数表达式的语法比函数短 表达式和不绑定自身的此,参数,超级,或 新建。目标。这些函数表达式最适用于非方法 函数,它们不能用作构造函数 你必须用你已经展示过的老方法Javascript对象中的Arrow函数,javascript,ecmascript-6,arrow-functions,Javascript,Ecmascript 6,Arrow Functions,我不明白为什么Javascript对象中的箭头函数似乎不起作用。如果查看上面的代码,第一个console.log将打印NaN,第二个将按预期打印数字 来自: 箭头函数表达式的语法比函数短 表达式和不绑定自身的此,参数,超级,或 新建。目标。这些函数表达式最适用于非方法 函数,它们不能用作构造函数 你必须用你已经展示过的老方法 let objNewWay = { width:400, height:300, area: () => this.width*this.height }
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
如果仍要使用arrow函数,则必须调用对象本身
let objNewWay={
宽度:400,
身高:300,
面积:()=>objNewWay.width*objNewWay.height
};
console.log(objNewWay.area());//NaN
来自:
箭头函数表达式的语法比函数短
表达式和不绑定自身的此,参数,超级,或
新建。目标。这些函数表达式最适用于非方法
函数,它们不能用作构造函数
你必须用你已经展示过的老方法
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
如果仍要使用arrow函数,则必须调用对象本身
let objNewWay={
宽度:400,
身高:300,
面积:()=>objNewWay.width*objNewWay.height
};
console.log(objNewWay.area());//NaN
不是lambda,您使用它的方式将引用与对象不同的范围
例如,从控制台:
area: function() {
return this.width*this.height;
}
如果要使用this
关键字,请使用区域:function(){}
方式。不是lambda,使用方式将引用与对象不同的范围
例如,从控制台:
area: function() {
return this.width*this.height;
}
如果您想使用
this
关键字,请使用区域:function(){}
方式。它的名称不是lamdaFrom MDN:两个因素影响了箭头函数的引入:较短的函数和this
的非绑定。谢谢。我将问题从lambda改为array function。arrow function,而不是array function。它的名称不是lamdaFrom MDN:两个因素影响了arrow functions的引入:较短的函数和this的非绑定。谢谢。我已将问题从lambda改为数组函数。箭头函数,而不是数组函数。谢谢。那么,造成差异的设计考虑因素是什么?@ElgsQianChen请点击文档链接-您将看到$No binding of this*@ElgsQianChen别忘了勾选答案谢谢。那么,造成差异的设计考虑因素是什么?@ElgsQianChen请点击文档链接-您将看到$No binding of this*@ElgsQianChen别忘了勾选答案