【发布时间】:2016-08-18 14:23:26
【问题描述】:
我对打字稿中的“this”关键字有疑问。正如您在下面看到的,我想从一些“内部”函数调用 method1,例如 FileReader.onloadend 方法。然而,'this' 引用 FileReader,而不是类 foo。如何更改我的代码以使其正常工作?
export class foo {
constructor() {
this.method2();
}
public method1() {
console.log('method1 called'); // this never happens
}
public method2() {
let reader: FileReader = new FileReader();
reader.onloadend = function(e) {
console.log(this) //it prints FileReader object
this.method1(); //I want this to be refered to class foo
}
}
}
【问题讨论】: