你可以绑定箭头功能吗? [英] Can you bind arrow functions?

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

问题描述

我一直在尝试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 do use them.

但是,看起来你不能绑定他们!

However, it would appear 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

var fBound = f.bind(o);

然后我可以调用 fBound

fBound();

哪个会输出这个( o 对象):

Which will output this (the o object):

{'a': 42}

酷!可爱!除了它不起作用。而不是输出 o 对象,它输出窗口对象。

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.

推荐答案

你不能重新绑定箭头函数。它将始终以其定义的上下文来调用。只需使用正常的功能。

You cannot "rebind" an arrow function. It will always be called with the context in which it was defined. Just use a normal function.

ECMASCRIPT 2015 Spec


一个ArrowFunction中的arguments,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.

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

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