TypeScript "this" scoping issue when called in jquery callback

Solution 1:

You have a few options here, each with its own trade-offs. Unfortunately there is no obvious best solution and it will really depend on the application.

Automatic Class Binding
As shown in your question:

class DemonstrateScopingProblems {
    private status = "blah";

    public run = () => {
        alert(this.status);
    }
}
  • Good/bad: This creates an additional closure per method per instance of your class. If this method is usually only used in regular method calls, this is overkill. However, if it's used a lot in callback positions, it's more efficient for the class instance to capture the this context instead of each call site creating a new closure upon invoke.
  • Good: Impossible for external callers to forget to handle this context
  • Good: Typesafe in TypeScript
  • Good: No extra work if the function has parameters
  • Bad: Derived classes can't call base class methods written this way using super.
  • Bad: The exact semantics of which methods are "pre-bound" and which aren't create an additional non-typesafe contract between your class and its consumers.

Function.bind
Also as shown:

$(document).ready(thisTest.run.bind(thisTest));
  • Good/bad: Opposite memory/performance trade-off compared to the first method
  • Good: No extra work if the function has parameters
  • Bad: In TypeScript, this currently has no type safety
  • Bad: Only available in ECMAScript 5, if that matters to you
  • Bad: You have to type the instance name twice

Fat arrow
In TypeScript (shown here with some dummy parameters for explanatory reasons):

$(document).ready((n, m) => thisTest.run(n, m));
  • Good/bad: Opposite memory/performance trade-off compared to the first method
  • Good: In TypeScript, this has 100% type safety
  • Good: Works in ECMAScript 3
  • Good: You only have to type the instance name once
  • Bad: You'll have to type the parameters twice
  • Bad: Doesn't work with variadic parameters

Solution 2:

Another solution that requires some initial setup but pays off with its invincibly light, literally one-word syntax is using Method Decorators to JIT-bind methods through getters.

I've created a repo on GitHub to showcase an implementation of this idea (it's a bit lengthy to fit into an answer with its 40 lines of code, including comments), that you would use as simply as:

class DemonstrateScopingProblems {
    private status = "blah";

    @bound public run() {
        alert(this.status);
    }
}

I haven't seen this mentioned anywhere yet, but it works flawlessly. Also, there is no notable downside to this approach: the implementation of this decorator -- including some type-checking for runtime type-safety -- is trivial and straightforward, and comes with essentially zero overhead after the initial method call.

The essential part is defining the following getter on the class prototype, which is executed immediately before the first call:

get: function () {
    // Create bound override on object instance. This will hide the original method on the prototype, and instead yield a bound version from the
    // instance itself. The original method will no longer be accessible. Inside a getter, 'this' will refer to the instance.
    var instance = this;

    Object.defineProperty(instance, propKey.toString(), {
        value: function () {
            // This is effectively a lightweight bind() that skips many (here unnecessary) checks found in native implementations.
            return originalMethod.apply(instance, arguments);
        }
    });

    // The first invocation (per instance) will return the bound method from here. Subsequent calls will never reach this point, due to the way
    // JavaScript runtimes look up properties on objects; the bound method, defined on the instance, will effectively hide it.
    return instance[propKey];
}

Full source


The idea can be also taken one step further, by doing this in a class decorator instead, iterating over methods and defining the above property descriptor for each of them in one pass.

Solution 3:

Necromancing.
There's an obvious simple solution that doesn't require arrow-functions (arrow-functions are 30% slower), or JIT-methods through getters.
That solution is to bind the this-context in the constructor.

class DemonstrateScopingProblems 
{
    constructor()
    {
        this.run = this.run.bind(this);
    }


    private status = "blah";
    public run() {
        alert(this.status);
    }
}

You can write an autobind method to automatically bind all functions in the constructor of the class:

class DemonstrateScopingProblems 
{

    constructor()
    { 
        this.autoBind(this);
    }
    [...]
}


export function autoBind(self)
{
    for (const key of Object.getOwnPropertyNames(self.constructor.prototype))
    {
        const val = self[key];

        if (key !== 'constructor' && typeof val === 'function')
        {
            // console.log(key);
            self[key] = val.bind(self);
        } // End if (key !== 'constructor' && typeof val === 'function') 

    } // Next key 

    return self;
} // End Function autoBind

Note that if you don't put the autobind-function into the same class as a member function, it's just autoBind(this); and not this.autoBind(this);

And also, the above autoBind function is dumbed down, to show the principle.
If you want this to work reliably, you need to test if the function is a getter/setter of a property as well, because otherwise - boom - if your class contains properties, that is.

Like this:

export function autoBind(self)
{
    for (const key of Object.getOwnPropertyNames(self.constructor.prototype))
    {

        if (key !== 'constructor')
        {
            // console.log(key);

            let desc = Object.getOwnPropertyDescriptor(self.constructor.prototype, key);

            if (desc != null)
            {
                if (!desc.configurable) {
                    console.log("AUTOBIND-WARNING: Property \"" + key + "\" not configurable ! (" + self.constructor.name + ")");
                    continue;
                }

                let g = desc.get != null;
                let s = desc.set != null;

                if (g || s)
                {
                    var newGetter = null;
                    var newSetter = null;
  
                    if (g)
                        newGetter = desc.get.bind(self);

                    if (s)
                        newSetter = desc.set.bind(self);

                    if (newGetter != null && newSetter == null) {
                        Object.defineProperty(self, key, {
                            get: newGetter,
                            enumerable: desc.enumerable,
                            configurable: desc.configurable
                        });
                    }
                    else if (newSetter != null && newGetter == null) {
                        Object.defineProperty(self, key, {
                            set: newSetter,
                            enumerable: desc.enumerable,
                            configurable: desc.configurable
                        });
                    }
                    else {
                        Object.defineProperty(self, key, {
                            get: newGetter,
                            set: newSetter,
                            enumerable: desc.enumerable,
                            configurable: desc.configurable
                        });
                    }
                    continue; // if it's a property, it can't be a function 
                } // End if (g || s) 

            } // End if (desc != null) 

            if (typeof (self[key]) === 'function')
            {
                let val = self[key];
                self[key] = val.bind(self);
            } // End if (typeof (self[key]) === 'function') 

        } // End if (key !== 'constructor') 

    } // Next key 

    return self;
} // End Function autoBind

Solution 4:

In your code, have you tried just changing the last line as follows?

$(document).ready(() => thisTest.run());