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; }}; } ());
Recent blog posts
- watir-webdriver web inspector
- gem list to gemfile
- Packing ruby2.0 on debian.
- Made it into The Guinness Book!
- to_h in ruby 2.0
- Filter elements by pattern jQuery.
- Better HTML password fields for mobile ?
- Grayscale image when user offline
- nth-child CSS pseudo-class Christmas colors
- EventEmitter in nodejs