Singleton design patterns ensures a class has only one instance and provide a global point to access it. Singleton pattern is handy when you want to create a class whose functionality does not required any changes for its multiple instances.
A basic singleton pattern can be created using simple object literal, because the created object itself will be an instance.
var singleTon = {
name: "Reality On Web",
location: "Delhi",
getInfo: function() {
console.log(singleTon.name);
console.log(singleTon.location);
}
}
Above example is very simple and easy to implement, but it is very limited as we cannot have private members in the object.
There are many ways of creating singleton design pattern. Depending on your specific need, If you don’t need private member then go with object literal approach.
var myObject = { }; // Singleton is done as in the above example
But to have a private members, it is required to create a class and then expose a method within the class which always returns the same instance.
There are no classes in javascript. But, function can behave like a class in JavaScript.
A very simple singleton pattern implementation
var singleton = new (function() {
var bar = 3;
this.foo = function() {
// whatever
}
})()
Here, we have just created a self invoking function using the new keywords, that contains private and public data members.
var singleTon = (function() {
var privateVar = '';
function privateMethod () {
// …
}
return { // this is your public interface
publicMethod1: function () {
// all private members are accessible here
},
publicMethod2: function () {
// all private members are accessible here
}
};
})();
Piyush Rishi Singh
www.piyushrishisingh.com
A Digital Entrepreneur & Content Creator who loves simplifying tech.
Expertise: A Full Stack & highly skilled 10+ years experienced WordPress developer who specializes in complete custom tailored WordPress Websites development.