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
...
}
}
}
我只是將它保存到一個局部變量以適當的名稱。 'var test = this;'或者其他什麼,所以你知道*哪個*「這個」,而不是'_this'。我更喜歡它通過'bind()',因爲它提高了JS回調箭頭代碼的可讀性。 – millimoose
@millimoose是的我知道我可以走這條路線,但似乎應該有更多的TS方式來做到這一點(除了使用'.bind(this)')。謝謝:) – John