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

Topics: General
May 31, 2013 at 12:31 AM

Let's say I have some code like this.
class MyClass {
  myString: string = "blah";
  func1() {
  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 3: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:

Andrew Gaspar

May 31, 2013 at 3:30 AM
func1() {, this.callback);
May 31, 2013 at 3: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 10:46 AM
func1() {
var result: CustomType = <CustomType>, this.callback);