我对 typescript 还很陌生,所以我有这个函数,它调用类构造函数内的另一个函数,但是当调用 this
时sayHelloAgain() 内部返回窗口对象
在 Greeter.init()
我正在打电话this.sayHello("message string", parameterCallback)
class Greeter {
init() {
this.sayHello("hello", this.sayHelloAgain);
}
sayHello(msg, callbackFunction) {
// Return Greeter object
console.log(this);
callbackFunction(msg);
}
sayHelloAgain(msg) {
// Returns Window object instead of Greeter
console.log(this)
}
}
let greeter = new Greeter("world");
最佳答案
this
是上下文相关的。在 sayHelloAgain
回调中,this
关键字不再代表类的实例。
您可以通过以下方式避免这种情况:
1 - 使用.bind(this)
this.sayHello("hello", this.sayHelloAgain.bind(this));
2 - 或者创建另一个调用回调的函数:
this.sayHello("hello", (msg) => this.sayHelloAgain(msg));
3 - 或者在回调中使用箭头函数
this.sayHello("hello", this.sayHelloAgain);
sayHelloAgain = (msg) => { /* ... */ }
关于javascript - Typescript:传递函数作为参数返回窗口对象而不是构造函数对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48622315/