2017-07-17 6 views
2

私は、オブジェクトを作成し、このようにそれに結合する必要がJavaScriptライブラリを使用したい:angular2タイスクリプトで「バインド」を正しく行うにはどうすればいいですか?

:私はこれをしたい、私は通常、typescriptですで .bind(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 
} 

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 
} 

.bind(this)はこの例では機能しません。これをどうやって回避するのですか? .bind(this)をやっているだけの選択肢がありますか?あるいは、typescript関数には何が使えますか?このような

this.webkitspeech.onresult = ($event) => { this.onresult($event) }; 

または使用bind

this.webkitspeech.onresult = this.onresult.bind(this); 

それとも機能をバインドするための最も便利な方法活字体ならびにES6で

答えて

4

は、コンテキストを維持するarrow functionを使用することです次のようにTSインスタンスの矢印関数(ESクラスのプロパティ)を使用できます。

class MyClass() { 
    onresult = ($event) => {...} 
    ... 
    this.webkitspeech.onresult = onresult; 
} 

クラスプロパティは今日、TSでサポートされているstage 2 ES7 proposalです。

See the documentationいくつかの方法を比較します。

+1

https://github.com/Microsoft/TypeScript/wiki/%27this%27-in-TypeScript#fixes – yurzui

+0

@yurzuiもお読みください。これは私が言及した3つの方法です。私は答えに参照を入れました –

+0

this.mystrへの参照を取得する方法は?定義されているか定義されていないWiIl? – Rolando

関連する問題