[英]How to properly do a “bind” in angular2 typescript?
I want to use a javascript library that requires creating an object and binding to it like this: 我想使用一个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
}
I would usually do a .bind(this)
我通常会做一个
.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
}
The .bind(this)
does not work in this example. .bind(this)
在此示例中不起作用。 How do I get around this? 我该如何解决这个问题? Are there alternatives to just doing
.bind(this)
? 有没有其他选择
.bind(this)
? Or whatever works for typescript functions? 或者什么适用于打字稿功能?
In TypeScript as well as in ES6 the most convenient way to bind a function is to use arrow function which preserves the context: 在TypeScript和ES6中,绑定函数最方便的方法是使用保留上下文的箭头函数 :
this.webkitspeech.onresult = ($event) => { this.onresult($event) };
Or use bind
like this: 或者像这样使用
bind
:
this.webkitspeech.onresult = this.onresult.bind(this);
Or you can use TS instance arrow function (ES class property) like this: 或者您可以使用TS实例箭头功能(ES类属性),如下所示:
class MyClass() {
onresult = ($event) => {...}
...
this.webkitspeech.onresult = onresult;
}
Class properties is stage 2 ES7 proposal which is supported in TS today. 类属性是第2阶段ES7提议 ,今天在TS中得到支持。
See the documentation for some comparison between the methods. 有关方法之间的一些比较, 请参阅文档 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.