I came across this rather interesting way to create a singleton JavaScript, which can be created using the new keyword, for example var x = new SingletonClass() . I'm pretty good at variables and closures, etc., but it's hard for me to understand why this block of code works the way it does.
// EDIT: DO NOT USE this code; see the answers below function SingletonClass() { this.instance = null; var things = []; function getInstance() { if (!this.instance) { this.instance = { add: function(thing) { things.push(thing); }, list: function() { console.log(things.toString()); } }; } return this.instance; } return getInstance(); } var obj1 = new SingletonClass(); obj1.add("apple"); obj1.list(); //"apple" var obj2 = new SingletonClass(); obj2.add("banana"); obj1.list(); //"apple,banana" obj2.list(); //"apple,banana" obj1.add("carrot"); obj1.list(); //"apple,banana,carrot" obj2.list(); //"apple,banana,carrot"
My intuition says that every time a new SingletonClass is created, this refers to this new new object, but after the constructor completely returns a separate object, I would think that this just gets discarded. But he hangs around. How? Why?
There are some tiniest details that I miss. Can anyone shed light on him?
EDIT: Turns out this code is bad. The reason it is "magically" seems to contain a reference to an instance is because it actually silently stores it in a global object. This is bad practice at best, and certainly error-prone.
smitelli
source share