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.
You cannot use bind
to change the value of this
inside an arrow function. However, you can create a new regular function that does the same thing as the old arrow function and then use call
or bind
to re-bind this
as usual.
We use an eval
call here to recreate the arrow function you pass in as a normal function and then use call
to invoke it with a different this
:
var obj = {value: 10};
function arrowBind(context, fn) {
let arrowFn;
(function() {
arrowFn = eval(fn.toString());
arrowFn();
}).call(context);
}
arrowBind(obj, () => {console.log(this)});