Saturday 15 April 2017

Rebinding 'this' for arrow functions in Node v7.9.x

I want to pass around a function and rebind the this. It works for some function types, but not others.

Here's my sample code:

class F {
  go (fxn) { fxn.apply(this, [1,2]) }
}

var f = new F();
f.foo = 'bar';
f.go(         () => { console.log(this.foo) }); // undefined
f.go(function ()    { console.log(this.foo) }); // "bar"

I understand that this is rebound to the caller's context in fat-arrow functions (and I'm so glad!). I would expect the normal behavior of .apply and .call to override this and re-bind this at runtime.

My question is: is there a way I can accomplish what I'm trying to do here with fat-arrow functions?



via Sir Robert

No comments:

Post a Comment