Bronzato
Bronzato

Reputation: 9332

With TypeScript: unable to refer to 'this' (class) from inside a function

I'm learning TypeScript and have the following class:

class DetailDriver {

    public get driver() {
        return super.getEntity();
    }

    public activate(): breeze.Promise {
        var id = this.driver.id(); // this refers to (class) DetailDriver

        return promise
            .then(getCertificate)
            .fail(somethingWrong);

        function getCertificate() {
            var id = this.driver.id(); // this refers to any
            return ...
        }
    }
}

As you can see on the above code, the first call to this refers to my class DetailDriver. That's good. The second call to this (inside getCertificate) refers to any. That's not what I need. I need to refer to my class DetailDriver.

How to proceed?

Thanks.

Upvotes: 3

Views: 2059

Answers (3)

Kevin Beal
Kevin Beal

Reputation: 10849

You could refactor to something like this:

class DetailDriver {

    public get driver() {
        return super.getEntity();
    }

    public activate(): breeze.Promise {
        var id = this.driver.id(); // this refers to (class) DetailDriver

        return promise
            .then(this.getCertificate.bind(this)) // <- important part
            .fail(somethingWrong);
    }

    // new method function here
    private getCertificate() {
        var id = this.driver.id(); // this refers to any
        return ...
    }
}

Using the function keyword anywhere in your class will make any reference to this keyword refer to that function rather than the outer class. Generally, you want to avoid defining functions inside of classes, unless you use the "fat arrow" syntax. That would look like this:

class DetailDriver {

    public get driver() {
        return super.getEntity();
    }

    public activate(): breeze.Promise {
        var id = this.driver.id(); // this refers to (class) DetailDriver

        return promise
            .then(() => { // <- important part
                var id = this.driver.id(); // this refers to any
                return ...
            })
            .fail(somethingWrong);
    }
}

Upvotes: 0

thoughtrepo
thoughtrepo

Reputation: 8383

For reference, you could also just do:

class SomeClass {

    public someMethod() {
        // Do something
    }
    public anotherMethod() {
        var that = this; // Reference the class instance

        function someFunction () {
            that.someMethod();
        }
    }
}

Upvotes: 1

stride
stride

Reputation: 1951

Well,

According to section 4.9.2 of the TypeScript Language Specification you should use fat arrow syntax to preserve the scoping for this.

return promise
        .then(() => return.this.id;)
        .fail(somethingWrong);

Then the this keyword is properly determined to be a Driver.

Upvotes: 8

Related Questions