如何正确地做“绑定”在angular2打字稿? [英] How to properly do a "bind" in angular2 typescript?
问题描述
我想使用一个需要创建对象并绑定到它的javascript库,如下所示:
I want to use a javascript library that requires creating an object and binding to it like this:
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)
虽然在打字稿中我想这样做:
Though in typescript I want to do 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)
?或者什么适用于打字稿函数?
The .bind(this)
does not work in this example. How do I get around this? Are there alternatives to just doing .bind(this)
? Or whatever works for typescript functions?
推荐答案
在TypeScript和ES6中,绑定函数最方便的方法是使用保留上下文的箭头功能:
In TypeScript as well as in ES6 the most convenient way to bind a function is to use arrow function which preserves the context:
this.webkitspeech.onresult = ($event) => { this.onresult($event) };
或者像这样使用 bind
:
this.webkitspeech.onresult = this.onresult.bind(this);
或者您可以使用TS实例箭头功能(ES类属性),如下所示:
Or you can use TS instance arrow function (ES class property) like this:
class MyClass() {
onresult = ($event) => {...}
...
this.webkitspeech.onresult = onresult;
}
类属性是第2阶段ES7提案。
请参阅文档,了解这些方法之间的比较。
See the documentation for some comparison between the methods.
这篇关于如何正确地做“绑定”在angular2打字稿?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!