A singleton in an object oriented language is where you have only have one object belonging to a given class. That single instance of the class is known as a singleton where the code is written in such a way as to not allow any additional objects to be defined from that class.
A prototyping language such as JavaScript does not have classes and so each and every object in JavaScript could be considered to be a singleton as we can never have two objects of the same class. We do have objects in JavaScript though which behave to some extent as if they were classes - at least when we have other objects inherit some or all of their properties and methods from that object. Considering all objects in JavaScript to be singletons is not therefore very useful. We might therefore consider a singleton in JavaScript to be an object that is defined in such a way that any attempts to create more than one object using the constructor function will result in the subsequent attempts just creating aliases for the object that was created the first time the constructor was called.
By adding the code shown in bold to the constructor function for any object we ensure that only the first call to the constructor (in this instance the call creating t1) actually creates a new object. The constructor tests if it has already been used to create an object and only actually creates the object if the object does not already exist. If the object has already been created by a prior call to the constructor then that previously created object will be returned instead of the function creating a new object (by returning the already existing once_only object instead of the new 'this' object). The line in this example that assigns a value to once_only.a represents whatever code you would normally have in the constructor if it were not a singleton.
function single(x) {
single.only = function() {
if (typeof one_only === 'undefined') one_only = this;
};
single.only();
one_only.a = x;
return one_only;
}
t1 = new single(1);
t2 = new single(2);
