3

我正在学习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 ...
        }
    }
}

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

如何进行?

谢谢。

4

3 回答 3

8

出色地,

根据 TypeScript Language Specification 的第 4.9.2 节,您应该使用粗箭头语法来保留范围。

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

然后 this 关键字被正确确定为驱动程序。

于 2013-09-13T10:48:06.073 回答
1

作为参考,您也可以这样做:

class SomeClass {

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

        function someFunction () {
            that.someMethod();
        }
    }
}
于 2013-09-17T16:32:08.947 回答
0

你可以重构为这样的东西:

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

在类中的任何地方使用function关键字将使对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);
    }
}
于 2016-09-21T18:06:55.563 回答