Reputation: 1
Using JavaScript ES6 I have several classes into which I want to separate the various concerns of my app. I have a main.js file in which I wish to instantiate the classes and then be able to reference and call methods across them.
My question is: What is the best/standard way to do this? My current approach is as follows;
In main.js I create an App class which instantiates two classes
import ClassOne from './ClassOne';
import ClassTwo from './ClassTwo';
export default class App {
constructor () {
this.one = new ClassOne(this);
this.two = new ClassTwo(this);
}
}
const app = new App();
Then in ClassOne.js I do something like this
export default class ClassOne {
constructor (app) {
this.app = app;
this.app.two.callMethod();
}
}
It certainly works, but does it look stoopid & is there a better way of doing it?
Upvotes: 0
Views: 209
Reputation: 68
I would suggest having a setter in ClassOne and ClassTwo. That way only ClassOne and ClassTwo are dependent on each other, and not on an instance of App.
ClassOne.js
export default class ClassOne {
setTwo (two) {
this.two = two;
this.two.callMethod();
}
}
ClassTwo.js
export default class ClassTwo {
setOne (one) {
this.one = one;
this.one.callMethod();
}
}
main.js
import ClassOne from './ClassOne';
import ClassTwo from './ClassTwo';
export default class App {
constructor () {
this.one = new ClassOne();
this.two = new ClassTwo();
this.one.setTwo(this.two);
this.two.setOne(this.one);
}
}
const app = new App();
Upvotes: 2