我编写了一个具有异步方法的类模块,现在我尝试使用 .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 改变范围?我可以阻止它吗?
这与字面定义中的范围无关。
this
这是关于以不同方式调用函数时值的绑定。问题是,当您
h.funcTwo
作为函数参数传递时,它会进入对象h
并获取对该函数的引用funcTwo
,并仅传递对该函数的引用,该函数将在没有任何引用的情况下被调用,并且根本h
不会与之关联。h
这意味着this
在该调用内部funcTwo()
will 是undefined
因为它没有被称为 ash.funcTwo()
。因此,正如您所发现的,可以使用
.bind()
传递一个函数存根来调用它,h.funcTwo()
而不仅仅是 asfuncTwo()
。您可以在这里看到一个更简单的示例: