I am looking to expand my JS code understanding down the path of OOP and I had some questions not only about performance but style.
To give an example, my Developer Tools: Dialog script (on userscripts.org) creates what is referred to as a singleton–a single instance that in this case can only be referenced under the “devtools.dialog” name. It is called (regardless of the script) by calling “devtools.dialog.method();”. Once that method is called, it stores the ID that was used into an array.
The problem is this:
Let’s say Script 1 calls the method and the ID is stored into that array. Script 2 calls the method and the ID is stored in the same array as Script 1. When Script 1 looks at the array, it sees the IDs from when it called the method but also from when Script 2 called the method.
What I would like to do:
Each script should be able to make a new instance (therefore having multiple instances) which is self-contained with only that instances settings.
From what I have looked at so far, I could do something like this which would allow for multiple instances, private variables/methods and of course public variables/methods:
// Define namespace.
if (typeof Container == 'undefined') {
Container = {};
}
// Set up the constructor.
Container.MyPlugin = function () {
// Private settings for this instance.
var settings = [...];
// Privelaged function to get private settings.
// From my understanding, this is added to memory with every instance. More instances = more functions added to memory.
this.getSettings = function () {
return settings;
}
};
// Public function for the plugin. Can't access the private settings, must use privelaged method.
// From my understanding, this is added to memory only once no matter how many instances are made.
Container.MyPlugin.prototype.doSomething = function () {
// Some code here.
};
// First instance.
var plugin = new Container.MyPlugin();
// Second instance, which means completely seperate settings.
var plugin2 = new Container.MyPlugin();
plugin.settings; // private...undefined
plugin.getSettings(); // privelaged...returns array
plugin.doSomething(); // public...can't access private stuff
Are there any better/more efficient ways of doing this type of thing? The above example wasn’t tested, it is just so I can get a better understanding while making it as simple as possible.