gpt4 book ai didi

javascript - 在 Promise 或 Callbacks (JavaScript ES6) 中处理此问题的正确方法

转载 作者:行者123 更新时间:2023-12-01 01:56:04 25 4
gpt4 key购买 nike

是否有正确或“更好”的方法来处理 this是 Promise 中的 JavaScript 类(甚至是回调)

目前我刚刚通过这样做来解决这个问题

 var self = this;

但这对我来说感觉很“hackey”。

忽略下面的大部分代码,这只是为了表达我的观点。

 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);

最佳答案

箭头函数将为您完成此操作。查看一些解释和 examples here .

这是一个更正的片段:

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);

关于javascript - 在 Promise 或 Callbacks (JavaScript ES6) 中处理此问题的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51033712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com