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.
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.
To be complete, you can re-bind arrow functions, you just can't change the meaning of this
.
bind
still has value for function arguments:
((a, b, c) => {
console.info(a, b, c) // 1, 2, 3
}).bind(undefined, 1, 2, 3)()
Try it here: http://jsbin.com/motihanopi/edit?js,console