你能在箭头函数中绑定“this"吗? [英] Can you bind 'this' in an arrow function?

查看:24
本文介绍了你能在箭头函数中绑定“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 对象):

Which will output this (the o object):

{'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.

来自 ECMAScript2015 规格:

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天全站免登陆