2
我想使用需要創建一個對象,這樣的結合給它的JavaScript庫:如何在angular2打字稿中正確做一個「綁定」?
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)
儘管在打字稿我想這樣做:
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)
?或者什麼適用於打字稿功能?
另請參見https://github.com/Microsoft/TypeScript/wiki/%27this%27-in-TypeScript#fixes – yurzui
@yurzui,謝謝,這些都是我提到的3種方法。我已將參考放入答案 –
如何獲得對this.mystr的引用? WiIl被定義或未定義? – Rolando