0

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.

sigil
  • 9,370
  • 40
  • 119
  • 199

2 Answers2

2

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());
    });
  }
Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38
1

You've got a scope problem. this in the post function is not referring to AnotherClass. You can get around this by storing the value in a variable before calling your post function:

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;
RyanDay
  • 1,856
  • 16
  • 23