Typescript + Jquery Ajax + this Typescript + Jquery Ajax + this typescript typescript

Typescript + Jquery Ajax + this


Can you just set self = this in the constructor and continue as you were before?

Speaking abstractly, doing this in the constructor will usually solve nothing (unless you capture it later on in that method -- see below). TypeScript classes store class instance data on the object itself rather than capturing locals. Because self will be stored on the this object, you don't end up having anything you didn't already have before.

Here's one way to do it:

class SomeAjaxService{    private FailureProxyCallback(context, arg) {        // now 'this' is the class instance and 'context' is requestArgs     }    public SendRequest(requestArgs) {        var self = this; // Note: captured local used in closure below        var ajaxSettings = {            context: requestArgs,            // Do not use an arrow function here, even though it's tempting!            error: function(arg) { self.FailureProxyCallback(this, arg) }        };        $.ajax(ajaxSettings);    };}