我正在学习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
(getCertificate
内)的第二次调用是指any
。那不是我需要的。我需要参考我的班级DetailDriver
。
如何进行?
感谢。
答案 0 :(得分:8)
那么,
根据TypeScript语言规范第4.9.2节,您应该使用胖箭头语法来保留范围。
return promise
.then(() => return.this.id;)
.fail(somethingWrong);
然后将此关键字正确确定为驱动程序。
答案 1 :(得分:1)
供参考,您也可以这样做:
class SomeClass {
public someMethod() {
// Do something
}
public anotherMethod() {
var that = this; // Reference the class instance
function someFunction () {
that.someMethod();
}
}
}
答案 2 :(得分: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);
}
}