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

半城伤御伤魂 提交于 2019-11-28 09:15:47

问题


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.


回答1:


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.




回答2:


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();
        }
    }
}



回答3:


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);
    }
}


来源:https://stackoverflow.com/questions/18783364/with-typescript-unable-to-refer-to-this-class-from-inside-a-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!