考虑此javascript:的Javascript的成员函数调用
let m = {
add: (a,b) => a+b,
subtract: (a,b) => a-b,
doit:() => console.log(this.add(5,4)),
};
m.doit();
当我运行这段代码,我得到以下错误:
doit:() => console.log(this.add(5,4)),
^
TypeError: this.add is not a function
什么是正确的方式来调用add
功能从doit
?
** Arrow功能**不结合'this'。一个常规函数:'doit:function(){console.log(this.add(5,4)); ''应该工作。 –
箭头函数内部的这个参数被绑定到了这个封闭类型。在上面的代码中,你可以用完整的“功能”函数来替换你的函数。或者你可以引用“m”而不是“this” –
解决这个问题的另一种方法是使用'm'而不是'this':'doit:()=> console.log(m.add(5,4 ))' –