Ad

Solutions For Binding JS Objects For Callbacks

- 1 answer

I find that it's very common to have code like (this is TypeScript, but the equivalent JS is fairly obvious and this is really a JS problem, although one that TS could solve):

class Foo {
    someField;

    someMethod() {
        doSomethingTakingACallback(function() {
            this.someField; // Fails because `this` is not the instance of `Foo`
        });
    }
}

The solution, of course, is to use Function.bind() like so:

    someMethod() {
        doSomethingTakingACallback(function() {
            this.someField; // Works as expected
        }.bind(this));
    }

Now the problem is that I have callbacks that must access the object instance a lot (ie, I need to be calling bind(this) on many callbacks). I've now wasted more time on bugs resulting from this than I'd like to admit. Is there some alternative? Am I missing some easier way to do this? Is there any reason that this is the default behavior as opposed to the function that we get from calling bind(this)?

One solution I know of is to do something like var me = this and then call me.someField (etc). It's a little nicer looking when I have many callbacks or nested callbacks. Although then I lose out on the iconicness of this, which I feel makes it the most clear where the member is located (on the class that I'm writing).

Ad

Answer

Typescript and ES6/ES2015 both support the "fat arrow function" syntax, which allows you to use this the way you do in most other languages - to refer to the class instance object.

e.g.

    someMethod() {
         doSomethingTakingACallback(() => {
             this.someField;
         });
    }

This compiles to the following code:

 Foo.prototype.someMethod = function () {
     var _this = this;
     doSomethingTakingACallback(function () {
        _this.someField;
     });
 };
Ad
source: stackoverflow.com
Ad