您可以在箭头功能中绑定"this"吗? [英] Can you bind 'this' in an arrow function?
问题描述
我已经在尝试使用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.
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屋!