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

时间秒杀一切 提交于 2019-11-29 15:25:12

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.

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

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