2016-04-25 11 views
2

を参照していません。typescriptの 'this'キーワードに問題があります。以下に示すように、私はmethod1をいくつかの '内部'関数、例えばFileReader.onloadendメソッドから呼び出す必要があります。 Hovewer、 'この' FileReaderへの参照ではなく、fooクラスへの参照です。このコードを変更するにはどうすればよいですか?typescriptのこのキーワードはクラス

export class foo { 

    constructor() { 
     this.method2(); 
    } 

    public method1() { 
     console.log('method1 called');   // this never happens 
    } 

    public method2() { 
     let reader: FileReader = new FileReader(); 

     reader.onloadend = function(e) { 
      console.log(this)     //it prints FileReader object 
      this.method1();     //I want this to be refered to class foo 
     } 
    } 
} 

答えて

2

がはるかに矢印で新しい関数リテラル構文を使用します。

public method2() { 
    let reader: FileReader = new FileReader(); 

    reader.onloadend = (e) => { 
     console.log(this) //it no longer prints FileReader object 
     this.method1(); //method1 called 
    } 
} 

ははるかに矢印を使用して、thisは今、常に代わりに関数スコープのクラスを指します。 Lexical thisと短い形式の関数構文の詳細については、MDNを参照してください。

ドキュメントはES6用ですが、厳密なスーパーセットであるため、Typescriptにも同じように適用されます。

1

変更この:これに

reader.onloadend = function(e) { 
    console.log(this)     //it prints FileReader object 
    this.method1();     //I want this to be refered to class foo 
} 

reader.onloadend = (e) => { 
    console.log(this)     //it prints FileReader object 
    this.method1();     //I want this to be refered to class foo 
} 

あなたは矢印機能hereについての詳細を読むことができます。

関連する問題