What is the simplest/cleanest way to implement singleton pattern in JavaScript?
I needed several singletons with:
and so this was what I came up with:
createSingleton ('a', 'add', [1, 2]);
console.log(a);
function createSingleton (name, construct, args) {
window[name] = {};
window[construct].apply(window[name], args);
window[construct] = null;
}
function add (a, b) {
this.a = a;
this.b = b;
this.sum = a + b;
}
args must be Array for this to work so if you have empty variables, just pass in []
I used window object in the function but I could have passed in a parameter to create my own scope
name and construct parameters are only String for window[] to work but with some simple type-checking, window.name and window.construct are also possible.