Reputation: 62596
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
}
I would usually do a .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. How do I get around this? Are there alternatives to just doing .bind(this)
? Or whatever works for typescript functions?
Upvotes: 12
Views: 17143
Reputation: 105439
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) };
Or use bind
like this:
this.webkitspeech.onresult = this.onresult.bind(this);
Or you can use TS instance arrow function (ES class property) like this:
class MyClass() {
onresult = ($event) => {...}
...
this.webkitspeech.onresult = onresult;
}
Class properties is stage 2 ES7 proposal which is supported in TS today.
See the documentation for some comparison between the methods.
Upvotes: 18