使用 TypeScript:无法从函数内部引用“this"(类) [英] With TypeScript: unable to refer to 'this' (class) from inside a function

查看:47
本文介绍了使用 TypeScript:无法从函数内部引用“this"(类)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 ...
        }
    }
}

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

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.

如何进行?

谢谢.

推荐答案

嗯,

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

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

那么this关键字就被正确判断为Driver了.

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

这篇关于使用 TypeScript:无法从函数内部引用“this"(类)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆