Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

javascript - Can you bind 'this' in an arrow function?

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!

Here is the function:

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

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

var o = {'a': 42};

And here is how I would bind f to o:

var fBound = f.bind(o);

And then I can just call fBound:

fBound();

Which will output this (the o object):

{'a': 42}

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?)


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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

From the ECMAScript 2015 Spec:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...