Search code examples
javascriptecmascript-6dependency-injectionrequirees6-class

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


To make instances of one ES6 class available in another, I've often used this structure:

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

class AnotherClass{

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

}

module.exports=AnotherClass;

However, I have a class where instead of importing the module in a require() above the class definition, I'm passing it into the constructor, then in the same class I'm creating an instance of that class for use in a REST endpoint:

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;

Which I want to do so that I can do dependency injection and pass in a version of Something with mock methods.

But the latter version is giving me this error:

TypeError: Cannot read property 'Something' of undefined

So I guess there's something wrong with how I am trying to pass the module into the constructor. How do I pass it in so that I can create instances of Something in the methods of AnotherClass?

EDIT: added code to show how I'm actually creating the instance of Something.


Solution

  • It's because you have used function in the app.post() endpoint. You need to use an arrow function in order to make this refer to the AnotherClass instance:

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