Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
-2
rated 0 times [  4] [ 6]  / answers: 1 / hits: 111012  / 9 Years ago, fri, october 23, 2015, 12:00:00

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.


More From » function

 Answers
28

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.



[#64622] Wednesday, October 21, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nikoguym

Total Points: 339
Total Questions: 106
Total Answers: 95

Location: Mali
Member since Sat, Feb 12, 2022
2 Years ago
;