Jake Wilson
Jake Wilson

Reputation: 91233

How to access parent methods from submodule?

I have the following module/class and submodule setup

MyAPI.js

class MyAPI {
  construction(){
    this.food = require('./Food');
  }
}
module.exports = MyAPI;

Food.js

class Food {
  constructor(){
    ...
  }
}
module.exports = Food;

app.js

var api = require('./MyAPI');
var taco = new api.food;
var cheeseburger = new api.food;

What I'm wondering, is it possible to call upon MyAPI properties and functions form within Food.js? Do I need to pass this into the require somehow?

this.food = require('./Food')(this); // this didn't work...

The above resulted in this:

TypeError: Class constructors cannot be invoked without 'new'

But why would I use new in the MyAPI constructor?

What is the best approach here to do subclasses and submodules and creating new objects from them?

Upvotes: 0

Views: 263

Answers (2)

Nick Tomlin
Nick Tomlin

Reputation: 29271

this.food is assigned in the constructor of MyApi, so you will need to instantiate MyApi to have the property accessible.

var Api = require('./MyAPI');
var apiInstance = new Api();
var foodInstance = new apiInstance.food();

From your comment, it seems like you want properties of MyApi, particularly config to be accessible by submodules. I don't see a way of doing this except to make your top level API object a singleton:

var MyAPI =  {
  config: { setting: 'default' },
  Food: require('./Food')
}

module.exports = MyAPI;
var MyApi = require('./my-api.js');

class Food {
  constructor(){
    // MyApi.config
  }
}
module.exports = Food;

Looking at the AWS source they are doing something similar (except config is it's own module mounted on the top level AWS object).

Upvotes: 0

mcgraphix
mcgraphix

Reputation: 2733

I think you are confusing classes and instances:

var MyAPI = require('./MyAPI');//this is a class
var apiInstance = new MyAPI();//the creates a new instance of your class
var taco = new apiInstance.food //the food property on your api is a class not an instance
var tacoInstance = new taco();

Upvotes: 1

Related Questions