javascript - 在 Promise 或 Callbacks (JavaScript ES6) 中处理此问题的正确方法
问题描述
是否有正确或“更好”的处理方式this
是带有 Promises(甚至是回调)的 JavaScript 类
目前我只是通过这样做来解决这个问题
var self = this;
但这对我来说感觉很“骇人听闻”。
忽略下面的大部分代码,这只是为了表达我的意思。
class thing {
drawthing(thing) {
console.log(thing);
}
updatethings(thing) {
var self = this; //a better way to do this
return new Promise(function (resolve) {
setTimeout(function(){
self.drawthing(thing);
return resolve(thing);
},2000);
});
}
}
var t = new thing();
t.updatethings('hello').then(console.log);
解决方案
箭头函数将为您完成此操作。在此处查看一些解释和示例。
这是一个更正的片段:
class thing {
drawthing(thing) {
console.log(thing);
}
updatethings(thing) {
// arrow func
return new Promise((resolve) => {
// another arrow func
setTimeout(() => {
// Because of arrow function scoping, `this` passes through.
this.drawthing(thing);
return resolve(thing);
},2000);
});
}
}
var t = new thing();
t.updatethings('hello').then(console.log);
推荐阅读
- ios - 反应本机语法错误“,”
- swift - 使用正确的百分号(即%)将百分号格式化为 zh(简体中文)
- css - 模糊“周围”文字
- php - php pdo update query not working properly
- jestjs - Use Jest expectations over the Detox custom ones
- php - PHP - Set boolean in function doesn't work
- python - Wagtail CMS not rendering navigation icons/images
- c - Issue when using pointer to line tokens in C
- python - MatplotlibDeprecationWarning: The rowNum and colNum attribute was deprecated in Matplotlib 3.2
- salesforce - Salesforce: How to automate report extraction as JSON/CSV