链接异步类方法,范围在何处以及为何发生变化?

问题描述 投票:0回答:1

我编写了一个具有异步方法的类模块,现在我尝试使用 .then() 链接这些方法

“this”的范围沿线某处发生变化,然后我必须将函数绑定回其实例才能恢复正确的范围。

class.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

script.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 改变范围?我可以阻止它吗?

node.js class asynchronous methods scope
1个回答
0
投票

这与范围无关。

问题是,当您将

h.funcTwo
作为函数参数传递时,它会进入
h
对象并获取对
funcTwo
的引用,并仅传递对该函数的引用。该引用与
h
根本没有关联。

因此,正如您所发现的,可以使用

.bind()
来传递一个函数存根,该函数存根将其称为
h.funcTwo()
而不是仅仅作为
funcTwo()

© www.soinside.com 2019 - 2024. All rights reserved.