简体   繁体   中英

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:

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM