passing a reference to a function doesn't maintain the 'this' keyword.

Topics: General
May 31, 2013 at 1:31 AM
Hi,

Let's say I have some code like this.
class MyClass {
  myString: string = "blah";
  func1() {
    someFunctionThatTakesACallback(this.func2);
  }
  func2(paramA: string, paramB: string, paramC: string): string {
    return this.myString;
  }
}
When func2() gets called 'this' is undefined. I know I could do something like this to fix the issue but I was wondering if there is a better (less verbose) solution.
someFunctionThatTakesACallback((paramA, paramB, paramC) => {
  this.func2(paramA, paramB, paramC);
});
May 31, 2013 at 4:30 AM
One option is to call it like: someFunctionThatTakesACallback(this.func2.bind(this)) - if your environment supports bind that is. Bind basically returns a function like what you proposed as an alternate solution. I'm not sure if bind is guaranteed in ES3 browsers.

A shim for bind in non-ES5 browsers is available in Mozilla's documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

Andrew Gaspar


May 31, 2013 at 4:30 AM
func1() {
someFunctionThatTakesACallback.call(this, this.callback);
}
May 31, 2013 at 4:50 AM
Andrew: Thanks for the info. I'll look into browser compatibility for bind.

PhotonStorm: Thanks, that works too. The only downside is that TypeScript doesn't know what the return type of call() is.
May 31, 2013 at 11:46 AM
func1() {
var result: CustomType = <CustomType> someFunctionThatTakesACallback.call(this, this.callback);
}
:)