I follow a module pattern where I instantiate components, however, a lot of time a component will only be instantiate one time (example: a comment system for an article).
For now I instantiate in the same JS file. but I was wondering if it is the wrong approach? It kind of make no sense to instantiate in the same file and always only once. But at the same time, if this file is in the page I want to have access to my module without instantiate from elsewhere, and IF I need another instance, I just create another from elsewhere…
Here is the pattern I follow:
ApplicationNamespace.Classname = function() {
// constructor
function privateFunctionInit() {
// private
}
this.privilegedFunction = function() {
// privileged
privateFunction();
};
privateFunctionInit()
};
ApplicationNamespace.Classname.prototype = {
Method: function(){}
}
var class = new ApplicationNamespace.Classname();
What do you think, wrong approach, or is this good?
I don’t think there’s anything inherently wrong with this. We have a lot of JS classes in the codebase at my job that uses this pattern. Even though you’re essentially using the class as a singleton, structuring it this way allows you to create more instances in the future with ease, should you ever need to.
In my own projects, I tend not to instantiate JS classes from within the file that defines them. I have a separate script that will instantiate whatever classes are needed on a page and work with them accordingly. That approach is probably more modular, but if you’re only ever using one instance, it’s mostly a matter of preference.
If you’re sure you’re never going to use more than one instance of the class, you could simplify things by creating a singleton object with object literal notation.