如何在angular2打字稿中正确执行"绑定"?

Rol*_*ndo 5 javascript angular

我想使用一个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
}
Run Code Online (Sandbox Code Playgroud)

我通常会这样做 .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
}
Run Code Online (Sandbox Code Playgroud)

.bind(this)不会在这个例子中工作.我该如何解决这个问题?只是做其他选择.bind(this)吗?或者什么适用于打字稿功能?

Max*_*kyi 9

在TypeScript和ES6中,绑定函数最方便的方法是使用保留上下文的箭头函数:

this.webkitspeech.onresult = ($event) => { this.onresult($event) };
Run Code Online (Sandbox Code Playgroud)

或者bind像这样使用:

this.webkitspeech.onresult = this.onresult.bind(this);
Run Code Online (Sandbox Code Playgroud)

或者您可以使用TS实例箭头功能(ES类属性),如下所示:

class MyClass() {
   onresult = ($event) => {...}
   ...
   this.webkitspeech.onresult = onresult;
}
Run Code Online (Sandbox Code Playgroud)

类属性是第2阶段ES7提议,今天在TS中得到支持.

有关方法之间的一些比较,请参阅文档.

  • 另见 https://github.com/Microsoft/TypeScript/wiki/%27this%27-in-TypeScript#fixes (2认同)