我想使用一个需要创建对象并绑定到它的JavaScript库,就像这样:
this.mystr = "hello";
this.webkitspeech = new webkitSpeechRecognition();
this.webkitspeech.onresult = function(evt) {
console.log(this.mystr); // this is undefined, even though I do have it defined
}
我通常会使用 .bind(this)
。
但在 TypeScript 中,我想这样做:
this.mystr = "hello"
this.webkitspeech = new webkitSpeechRecognition();
this.webkitspeech.onresult = onresult;
onresult(event) {
console.log(this.mystr) // this is undefined, even though I do have it defined
}
.bind(this)
在这个示例中不起作用。 我该怎么解决? 除了使用.bind(this)
之外,还有其他的选择吗? 或者对于typescript函数,有什么方法可以解决问题?
this
将指向类实例,因此您将可以访问所有class
成员,包括mystr
。 - Max Koretskyi