在 traverse
npm 包中有这个例子
var obj = [ 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ];
traverse(obj).forEach(function (x) {
if (x < 0) this.update(x + 128);
});
在回调函数中你可以调用this.update
。我知道在这些情况下,您应该使用如上所示的常规(不是 ES6 箭头)样式的函数定义。
但出于好奇,您如何使该代码使用 ES6 箭头函数语法?如果我按如下方式尝试,我会得到 TypeError: Cannot read property 'update' of undefined
因为当然 this
与上面的不一样。
traverse(obj).forEach((x) => {
if (x < 0) this.update(x + 128);
});
我尝试使用 bind
更改 this
但没有成功。如何在 ES6 箭头函数中更改 this
?
最佳答案
How do you change
this
in ES6 arrow functions?
你不能,这就是使用箭头函数的全部意义(除了简洁的语法)。如果您需要控制 this
,请不要使用箭头函数。
关于javascript - 如何更改 ES6 箭头函数的 'this' 指向的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33723263/