如何更改ES6箭头功能的“这”指向什么? [英] How to change what an ES6 arrow function's 'this' points to?

查看:124
本文介绍了如何更改ES6箭头功能的“这”指向什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

遍历 npm包中有这个例子

In the traverse npm package there's this example

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箭头)的函数定义。

Inside the callback function you can call this.update. I know in these kinds of cases you should use the regular (not ES6 arrow) style of function definitions like shown above.

但出于好奇,你会如何代码使用ES6箭头函数语法?如果我尝试如下,我得到 TypeError:由于当然不能读取未定义的属性'update'这个不是

But out of curiosity, how would you make that code work with ES6 arrow function syntax? If I try as follows I get TypeError: Cannot read property 'update' of undefined because of course this is not the same as above.

traverse(obj).forEach((x) => {
    if (x < 0) this.update(x + 128);
});

我尝试通过使用 code> bind 但不成功。如何在ES6箭头函数中更改这个

I tried to change this by using bind but wasn't successful. How do you change this in ES6 arrow functions?

推荐答案


如何在ES6箭头函数中更改这个

你不能,这就是使用箭头函数的全部要点(除了简洁的语法)。如果您需要控制,请勿使用箭头功能。

You can't, that's the whole point of using arrow functions (besides concise syntax). If you need to control this, don't use an arrow function.

这篇关于如何更改ES6箭头功能的“这”指向什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆