Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
158 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...