I want a JavaScript class that can conditionally add additional methods into itself from separate files. The idea is to separate different concerns of the app into more manageable self-contained modules that nevertheless can interact with the methods in the mother app class. Therefore, the additional methods in the separate file must be able to reference the methods and variables in the main class. See the code sample below.
I looked at a lot of different solutions, but all of them have a downside for what I'm wanting.
- I could do
new Uploads()
, but I could not find a way for methods inUploads.js
to reference methods in the mainApp
class - I could use
extends
, but this would not allow for conditional extension AFAIK - I could just define new methods into the prototype itself, but this would mean that the external file would need to "know" about the class it's going to be used in, which doesn't make it widely reusable.
The best I have so far is the following:
app.js
const Uploads = require("./Uploads.js");
const config = { hasUploads: true }; // Probably loaded from a file
class App {
constructor() {
/* Only include the separate module if the config says so */
if(config.hasUploads) {
Object.assign(this, Uploads);
}
}
foo() {
/* Something */
}
}
Uploads.js
module.exports = {
bar() {
this.foo();
}
};
It works, but I don't know if this is the best solution;
- There's no constructor, so if
Uploads.js
needs to do some setup,app.js
needs to contain the logic to do so (or at least know to call some uniquely named faux constructor method), which doesn't seem ideal. - If
Uploads.js
contains a method with the same name asapp.js
or any other possible module being loaded, they will be overwritten, leading into unexpected behaviour. - The
Uploads.js
is an object of functions, whereasapp.js
defines a class. Ideally (though I guess not necessarily) for code manageability they should both use the same syntax.
Is there a better/cleaner/nicer way of doing this?