2016-04-25 82 views
2

我在打字稿中的'this'關鍵字有問題。正如你在下面看到的,我想從一些'內部'函數調用method1,例如FileReader.onloadend方法。 Hovewer,'this'引用FileReader,而不是foo類。我怎樣才能改變我的代碼來完成這項工作?打字稿中的這個關鍵字並不涉及類

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現在總是指的是類,而不是函數範圍內。您可以查看MDN以獲取有關Lexical this和簡短格式函數語法的更多信息。

該文檔適用於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