我编写了一个具有异步方法的类模块,现在我尝试使用 .then() 链接这些方法
“this”的范围沿线的某个地方发生了变化,然后我必须将函数绑定回其实例才能恢复正确的范围。
类.js
class Asdf {
#asdf;
constructor(){
this.#asdf = 'asdf'
}
async funcOne(){
// h.funcOne().then // works fine
return this.#asdf
}
async funcTwo(a){
// .then(h.funcTwo) // this.funcThree becomes undefined?
// where does the scope change??
var x = await this.funcThree(a)
return x
}
async funcThree(a){
return a
}
}
module.exports = Asdf
脚本.js
var h = new (require('./class.js'));
h.funcOne().then(h.funcTwo) // scope is changed, code breaks, claiming undefined
h.funcOne().then(h.funcTwo.bind(h)) // works because we re-bind the scope
// Where and Why does the Scope Change??
为什么使用 .then 改变范围?我可以阻止它吗?