Singleton Pattern in JavaScript
What is Singleton Pattern?
The singleton pattern is a design pattern that restricts the instantiation of a class to one object, much inspired from singleton set {0}.
Where is it useful?
-
Controlling concurrent access to a shared resource.
-
Abstract Factory implementation.
-
One time read variables. etc
What is the use of it?
Well despite the arguments and down votes for Singleton Pattern, it’s still surviving! And in JS it’s useful for :
-
Encapsulation of members & functions.
-
Creating Namespace.
-
Encourages code reuse.
-
Logically organisation of code gets easier.
Singleton implementation with JavaScript :
function SalarySingleton() {
if (typeof Singleton.salary === ‘object’) {
return Singleton.salary;
}
this.setSalary = function(amt) {
this.amt = amt;
} this.getSalary = function() {
return this.amt;
}
Singleton.salary = this;
}
var emp1 = new SalarySingleton(); emp1.setSalary(60000);
Do express your <3 towards singleton pattern!
EDIT 0 : iife to avoid new.
var singleton = (function () {
var amt;
return {
getSalary: function () { return amt; },
setSalary: function (amount) { amt = amount; }};
}
());
About Hemanth HM
Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.