gpt4 book ai didi

typescript - typescript 中的这个关键字不引用类

转载 作者:搜寻专家 更新时间:2023-10-30 21:30:55 24 4
gpt4 key购买 nike

我对 typescript 中的“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
}
}
}

最佳答案

使用带远箭头的新函数文字语法:

public method2() {
let reader: FileReader = new FileReader();

reader.onloadend = (e) => {
console.log(this) //it no longer prints FileReader object
this.method1(); //method1 called
}
}

使用远箭头,this 现在总是引用类,而不是函数作用域。您可以查看 MDN有关词法 this 和短形式函数语法的更多信息。

该文档适用于 ES6,但它同样适用于 Typescript,因为它是一个严格的超集。

关于typescript - typescript 中的这个关键字不引用类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36836431/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com