“this”和内部作用域命名函数的打字稿问题
Typescript issue with 'this' and inner scoped named function
写这个的正确方法是什么?
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(this) 是正确的方式吗?
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
...
}
}
}
我会建议这样的事情:
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);
}
}
相关文章:
- Javascript时间函数问题
- Javascript Array 的求和函数问题
- Jshint:循环中的匿名函数(问题)
- WordPress FAQ 手风琴自定义帖子类型 - 匿名函数问题.
- JavaScript 中的滚动函数问题
- Google JS API: gapi.auth.signIn 回调函数问题
- Javascript onclick 函数问题
- Javascript中的循环和函数问题
- 达到 10 次摘要迭代,中止(作用域函数问题)
- 洛达什 _.合并函数问题
- jQuery .unload() 函数问题,仅在单击特定链接时激活
- 回调函数问题
- Javascript语法函数问题
- Ajax 完整函数问题
- TypeError getElementsByTagName不是函数问题
- Jquery自定义函数问题
- angularjs编译指令中的函数问题
- JQuery-JNotify-点击函数问题
- Node Js中的回调函数问题
- javascript中的ie8拆分函数问题