使用TypeScript:无法从函数内部引用"this"(类)

Bro*_*ato 3 this typescript

我正在学习TypeScript并有以下课程:

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 ...
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

正如您在上面的代码中看到的,第一次调用是this指我的类DetailDriver.非常好.对this(内部getCertificate)的第二次调用是指any.那不是我需要的.我需要参考我的课程DetailDriver.

如何进行?

谢谢.

str*_*ide 8

好,

根据TypeScript语言规范的4.9.2节,您应该使用胖箭头语法来保留此范围的范围.

return promise
        .then(() => return.this.id;)
        .fail(somethingWrong);
Run Code Online (Sandbox Code Playgroud)

然后,将此关键字正确确定为驱动程序.