javascript - 如何更改 ES6 箭头函数的 'this' 指向的内容?

标签 javascript node.js callback this ecmascript-6

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/

相关文章:

javascript - Vue.js Electron : Synchronize variables between backend and frontend

javascript - 为什么我的计算器会连接而不是执行运算?

javascript - moment.js - isBetween() 方法不能始终如一地工作

node.js - Node : Hit endpoint that returns a CSV file and send the contents to client

node.js - Node JS 中的 FIWARE OAuth2 身份验证

android - 在 Android 中使用 android plaid sdk 未收到成功回调

javascript - 取消之前调用的 Google Maps geocode 方法

javascript - 异步 JavaScript 解决方法

javascript - 如何跨浏览器检测在线/离线事件?

javascript - 从数组javascript更改对象数组中的值