![](/img/trans.png)
[英]How to do authentication for pages using angular2 and typescript
[英]How to properly do a “bind” in angular2 typescript?
我想使用一个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)
虽然在打字稿中我想这样做:
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和ES6中,绑定函数最方便的方法是使用保留上下文的箭头函数 :
this.webkitspeech.onresult = ($event) => { this.onresult($event) };
或者像这样使用bind
:
this.webkitspeech.onresult = this.onresult.bind(this);
或者您可以使用TS实例箭头功能(ES类属性),如下所示:
class MyClass() {
onresult = ($event) => {...}
...
this.webkitspeech.onresult = onresult;
}
类属性是第2阶段ES7提议 ,今天在TS中得到支持。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.