Since JavaScript doesn't have any classes, each object you create can be considered to be a singleton. Since we can use objects in place of classes in JavaScript, what you probably want to happen regarding creating a singleton it to be able to use multiple commands for creating new objects based on an existing one and have all of those end up just referencing the original single object.
What we want in order to get the proper effect of a singleton object is to be able to have code such the following with both t1 and t2 ending up as references to the same object.:
var t1 = new single(1);
var t2 = new single(2);
In order for those two calls to end up both referencing the same object we need to have some way within the code itself to determine whether we have already created an object and if so to return the existing object rather than a new one. There are three ways we can do this - we can use a global variable, we can use a public property, or we can use a private property to track whether the object already exists. The third of these is the preferred way to do this since a global or public property can be easily overwritten resulting in our losing the object completely.
To create our singleton using a private property we need to use what we have learnt in several of the preceding tutorials. I'll save you the trouble of going back through them though by presenting the complete code to create a singleton object called single where we use a private property called once_only to track our singleton object for us. In the following code I have included receiving a value in an argument called "x" and using it to set the value of a property called "a" so that you can easily see that when we set the value to 2 in creating the t2 object that when we retrieve the "a" property from the t1 object that it contains the 2 that was just set and not the 1 we set when we created that object.
Here is the complete singleton code.
function single(x) {
single.only = function() {
if (typeof one_only === 'undefined') one_only = this;
};
single.only();
one_only.a = x;
return one_only;
}
var t1 = new single(1);
var t2 = new single(2);
alert(t1.a); // replies "2"
All the Object Oriented JavaScript Tutorials
- What is Object Oriented JavaScript?
- The Benefits of OO JavaScript
- JavaScript's Built in Objects
- Extending Built In Objects
- Creating Objects from Existing Objects
- Creating New Objects Without Copying Existing Ones
- Dot Notation and "this"
- prototype
- Inheritance and "constructor"
- Associative Array Notation
- Create Method if Doesn't Exist
- "self" and Multiple Objects
- Defining Objects with JSON
- Namespaces
- Lazy Definition
- Extending Methods
- Copying Objects
- Private Properties and Privileged Methods
- Public Access to Private Methods
- Chaining Methods
- Singletons

