Using TypeScript: it is not possible to reference 'this' (class) from inside a function

I study TypeScriptand 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 from the above code, the first call thisrefers to my class DetailDriver. It's good. The second call this(inside getCertificate) refers to any. This is not what I need. I need to contact my class DetailDriver.

How to act?

Thank.

+3
source share
3 answers

Well,

In accordance with Section 4.9.2 of the TypeScript language specification, you should use the strong arrow syntax to maintain the scope for this.

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

Then this keyword is correctly defined as a driver.

+8

:

class SomeClass {

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

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

You can reorganize 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 a keyword functionanywhere in your class will make the keyword thislink a link to this function, not an external class. Typically, you want to avoid defining functions inside classes unless you use the thick arrow syntax. It will 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);
    }
}
0
source

All Articles