我已经尝试使用 ES6 一段时间了,但我遇到了一个小问题。
我真的很喜欢使用箭头函数,只要有可能,我就会使用它们。
但是,您似乎无法绑定(bind)它们!
函数如下:
var f = () => console.log(this);
这是我要将函数绑定(bind)到的对象:
var o = {'a': 42};
下面是我如何将 f
绑定(bind)到 o
:
var fBound = f.bind(o);
然后我可以调用fBound
:
fBound();
这将输出这个(o
对象):
{'a': 42}
太棒了!迷人的!除了它不起作用。它不输出 o
对象,而是输出 window
对象。
所以我想知道:你能绑定(bind)箭头函数吗? (如果是,怎么做?)
我在谷歌浏览器 48 和火狐浏览器 43 上测试了上面的代码,结果是一样的。
最佳答案
您不能在箭头函数中重新绑定(bind) this
。它将始终被定义为定义它的上下文。如果您需要 this
有意义,您应该使用普通函数。
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.
关于javascript - 你能在箭头函数中绑定(bind) 'this' 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33308121/