您可以在箭头功能中绑定"this"吗? [英] Can you bind 'this' in an arrow function?

查看:78
本文介绍了您可以在箭头功能中绑定"this"吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在尝试使用ES6一段时间了,但是我遇到了一个小问题.

I've been experimenting with ES6 for a while now, and I've just come to a slight problem.

我真的很喜欢使用箭头功能,只要有可能,我就使用它们.

I really like using arrow functions, and whenever I can, I use them.

但是,您似乎无法绑定它们!

However, it would appear that you can't bind them!

这是函数:

var f = () => console.log(this);

这是我要将功能绑定到的对象:

Here is the object I want to bind the function to:

var o = {'a': 42};

这是我将f绑定到o的方式:

And here is how I would bind f to o:

var fBound = f.bind(o);

然后我可以打电话给fBound:

fBound();

哪个将输出(o对象):

{'a': 42}

酷!迷人的!除非它不起作用.代替输出o对象,它输出window对象.

Cool! Lovely! Except that it doesn't work. Instead of outputting the o object, it outputs the window object.

所以我想知道:您可以绑定箭头功能吗? (如果是这样,怎么办?)

So I'd like to know: can you bind arrow functions? (And if so, how?)

我已经在Google Chrome 48和Firefox 43中测试了上面的代码,结果是相同的.

I've tested the code above in Google Chrome 48 and Firefox 43, and the result is the same.

推荐答案

箭头功能不能重新绑定 this.它将始终被定义为定义它的上下文.如果您要求this有意义,则应使用常规功能.

You cannot rebind this in an arrow function. It will always be defined as the context in which it was defined. If you require this to be meaningful you should use a normal function.

来自 ECMAScript 2015年规格:

ArrowFunction中对参数,super,this或new.target的任何引用都必须解析为词法包围环境中的绑定.通常,这将是立即封闭函数的函数环境.

Any reference to arguments, super, this, or new.target within an ArrowFunction must resolve to a binding in a lexically enclosing environment. Typically this will be the Function Environment of an immediately enclosing function.

这篇关于您可以在箭头功能中绑定"this"吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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