13

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?

1 Answer 1

21

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.

Sign up to request clarification or add additional context in comments.

4 Comments

@yurzui, thanks, these are the 3 methods I've mentioned as well. I've put the reference into the answer
What about how to get a reference to this.mystr? WiIl that be defined or undefined?
@Rolando, this will pointing to the class instance so you will have access to all class members including mystr

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.