2013-12-18 18 views
0

寫這個的正確方法是什麼?使用'this'和內部作用域命名函數的Typescript問題

class Test { 
    log(data) { ... } 
    queryFailed(error) { ... } // Generic error handler 
    runQuery(data) { 
     doStuff() 
     .then(querySuccess) 
     .catch(this.queryFailed); 

     function querySuccess(data) { // query specific success handler 
      this.log("Success!"); // "this" is undefined 
      ... 
     } 
    } 
} 

我知道我能做到像內聯:

class Test { 
    log(data) { ... } 
    queryFailed(error) { ... } // Generic error handler 
    runQuery(data) { 
     doStuff() 
     .then((data) => { 
      this.log("Success!"); // 'this' is really '_this' now and set to 'this' right above 'doStuff()' in the compiled javascript 
      ... 
     }) 
     .catch(this.queryFailed); 

     function querySuccess 
    } 
} 

但遮住了邏輯從doStuff()

的結果使用.bind(本)內嵌的正確方法?

class Test { 
    log(data) { ... } 
    queryFailed(error) { ... } // Generic error handler 
    runQuery(data) { 
     doStuff() 
     .then(querySuccess.bind(this)) 
     .catch(this.queryFailed); 

     function querySuccess(data) { // query specific success handler 
      this.log("Success!"); // "this" works 
      ... 
     } 
    } 
} 
+0

我只是將它保存到一個局部變量以適當的名稱。 'var test = this;'或者其他什麼,所以你知道*哪個*「這個」,而不是'_this'。我更喜歡它通過'bind()',因爲它提高了JS回調箭頭代碼的可讀性。 – millimoose

+0

@millimoose是的我知道我可以走這條路線,但似乎應該有更多的TS方式來做到這一點(除了使用'.bind(this)')。謝謝:) – John

回答

0

我建議是這樣的:

class Test { 
    log(data) { } 
    static queryFailed(error) { } // Make sure we don't try to use 'this' here 
    runQuery(data) { 
     var querySuccess = data => { // query specific success handler 
      this.log("Success!"); // Correct 'this' 
     } 

     doStuff() 
     .then(querySuccess) 
     .catch(Test.queryFailed(error)); 
    } 
} 

或者:

class Test { 
    log(data) { } 
    static queryFailed(error) { } 
    querySuccess = (data) => { 
     this.log('Success'); 
    } 
    runQuery(data) { 
     doStuff() 
     .then(this.querySuccess) 
     .catch(Test.queryFailed); 
    } 
} 
+0

我需要querySuccess是特定於父功能,因爲它會有特定的東西,如分配變量或其他東西。 queryFailed是通用的,只會顯示失敗的消息或w/e。 – John

相關問題