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

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

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

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

class AnotherClass{

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

}

module.exports=AnotherClass;

但是,我有一个类,而不是将模块导入类定义上方的require()中,而是将其传递给构造函数,然后在同一类中创建该类的实例以用于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

因此,我想将模块传递给构造函数的方式有问题。如何传递它,以便可以在Something的方法中创建AnotherClass的实例?

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

javascript ecmascript-6 dependency-injection require es6-class
2个回答
1
投票

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

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

0
投票

您遇到范围问题。发布功能中的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;
© www.soinside.com 2019 - 2024. All rights reserved.