如果我将其模块传递给构造函数而不是要求它,如何创建 class 的实例?

How to create an instance of a class if I'm passing its module into the constructor instead of requiring it?

为了使一个 ES6 class 的实例在另一个中可用,我经常使用这种结构:

const Something=require('./something');

class AnotherClass{

  makeASomething(){
      var outputSomething=new Something();
      return outputSomething;
  }

}

module.exports=AnotherClass;

但是,我有一个 class,我不是在 class 定义上方的 require() 中导入模块,而是将它传递给构造函数,然后在相同的class 我正在创建 class 的实例以用于 REST 端点:

class AnotherClass{

  constructor(Something){
      this.Something=Something;
  }


  initialize(app){
    app.post('/sendSomething',async function(req,res){
        const response=new this.Something();
        res.end(response.toString());
    });
  }



  makeASomething(){
      var outputSomething=new this.Something();
      return outputSomething;
  }

}

module.exports=AnotherClass;

我想这样做,以便我可以进行依赖注入并使用模拟方法传入 Something 版本。

但是后一个版本给我这个错误:

TypeError: Cannot read property 'Something' of undefined

所以我想我尝试将模块传递给构造函数的方式有问题。我如何传递它以便我可以在 AnotherClass?

的方法中创建 Something 的实例

编辑:添加代码以显示我实际上是如何创建 Something 的实例的。

你遇到了范围问题。 post 函数中的 this 不是指 AnotherClass。您可以通过在调用 post 函数之前将值存储在变量中来解决此问题:

class AnotherClass{

constructor(Something){
    this.Something=Something;
}


initialize(app){

    const _something = this.Something;

    app.post('/sendSomething',async function(req,res){

        const response=new _something();

        res.end(response.toString());
    });
}



makeASomething(){
    var outputSomething=new this.Something();
    return outputSomething;
}

}

module.exports=AnotherClass;

这是因为您在 app.post() 端点中使用了 function。您需要使用箭头函数才能使 this 引用 AnotherClass 实例:

  initialize(app){
    app.post('/sendSomething', async (req, res) => {
        const response = new this.Something();
        res.end(response.toString());
    });
  }