class Util
{
callback(callme: () => void)
{
callme();
}
}
class Greeter {
greeting: string;
util: Util;
Me : Greeter;
constructor(message: string) {
this.greeting = message;
this.util = new Util();
}
greet() {
return "Hello, " + this.greeting;
}
callMe()
{
this.util.callback(this.greet);
}
}
var greeter = new Greeter("world");
var button = document.createElement('button');
button.textContent = "Say Hello";
button.onclick = function() {
alert(greeter.callMe());
}
document.body.appendChild(button);
我在使用 this 关键字时遇到问题,当我执行这样的代码时,它没有指向该类。如何使这个应用程序工作?当在像这样的回调中使用时,this 指向窗口...
最佳答案
更改为
this.util.callback(this.greet.bind(this));
问题是,当您传递对greet方法的引用时,JavaScript只会看到一个函数作为参数传递。当函数执行时,它需要一个新的上下文,并使用“this”此时代表的任何内容。
为了避免这种情况,您可以将函数绑定(bind)到其上下文,并避免在执行时为其分配新的上下文。为此,您可以使用bind
。它的第一个参数允许您定义执行函数时应使用的上下文对象。
这在某种程度上相当于:
var self = this;
this.utils.callback(function(){
self.greet();
});
这相当于您使用 TypeScript 闭包在评论中得到的答案
() => this.greet();
关于typescript - 回调中的 this 关键字不适用于 typescript ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23980711/