typescript中的这个关键字不';I don’我指的是课堂
我对typescript中的“this”关键字有问题。正如您在下面看到的,我想从一些“内部”函数调用method1,例如FileReader.onloadend方法。Hovewer,“this”引用文件阅读器,而不是类foo。如何更改代码以使其正常工作typescript中的这个关键字不';I don’我指的是课堂,typescript,typescript1.8,Typescript,Typescript1.8,我对typescript中的“this”关键字有问题。正如您在下面看到的,我想从一些“内部”函数调用method1,例如FileReader.onloadend方法。Hovewer,“this”引用文件阅读器,而不是类foo。如何更改代码以使其正常工作 export class foo { constructor() { this.method2(); } public method1() { console.log('method1 called
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
}
}
}
使用带有远箭头的新函数文字语法:
public method2() {
let reader: FileReader = new FileReader();
reader.onloadend = (e) => {
console.log(this) //it no longer prints FileReader object
this.method1(); //method1 called
}
}
使用远箭头,这个
现在总是指向类,而不是函数范围。有关词法this
和缩写函数语法的更多信息,请查看
本文档适用于ES6,但它同样适用于Typescript,因为它是一个严格的超集。更改此项:
reader.onloadend = function(e) {
console.log(this) //it prints FileReader object
this.method1(); //I want this to be refered to class foo
}
为此:
reader.onloadend = (e) => {
console.log(this) //it prints FileReader object
this.method1(); //I want this to be refered to class foo
}
您可以阅读有关箭头函数的更多信息