I've decided to write more OOP articles in WinJS library regarding the use of Design Patterns we all love! You can learn my previous parts:
Let's start with what this design pattern means.
What is Singleton Design Pattern?
Singleton is one of the most widely used design patterns in Javascript. It mainly creates only one instance of the object which lets you call it globally.
If you want to declare global variables across the js app,Singleton pattern is just for you
According to DoFactory,Singleton Pattern includes only one object:
Singleton object defines a function named getInstance() which returns you a unique instance.
getInstance implements another pattern named "Lazy Load".
What is Lazy Load?
Lazy Load checks if an object's instance has already been created if not it creates one immediately.This is called Lazy Load.
Singleton object defines a function named getInstance() which returns you a unique instance.
getInstance implements another pattern named "Lazy Load".
What is Lazy Load?
Lazy Load checks if an object's instance has already been created if not it creates one immediately.This is called Lazy Load.
Since there's only one object, why don't we simply implement it?
Implementation
Create a Singleton object as follows:
As previously stated,I also commented getInstance() using Lazy Load for instance checking.
We created an object named "Ibrahim Ersoy" and set its value to instance.
- var Singleton = WinJS.Class.define(function () {
- var instance;
- function createInstance() {
- var object = new Object("Ibrahim Ersoy");
- return object;
- }
- //Lazy Load Section Start
- return {
- getInstance: function () {
- if (!instance) {
- instance = createInstance();
- }
- return instance;
- }
- };
- //Lazy Load Section End
- })();
We created an object named "Ibrahim Ersoy" and set its value to instance.
To call this pattern use code as follows:
- var dev1 = Singleton.getInstance();
- var dev2 = Singleton.getInstance();
- console.log("Are you both Ibrahim Ersoy? " + (dev1 === dev2));
Lets see the output it displays:
Full Code:
- var Singleton = WinJS.Class.define(function () {
- var instance;
- function createInstance() {
- var object = new Object("Ibrahim Ersoy");
- return object;
- }
- //Lazy Load Section Start
- return {
- getInstance: function () {
- if (!instance) {
- instance = createInstance();
- }
- return instance;
- }
- };
- //Lazy Load Section End
- })();
- var dev1 = Singleton.getInstance();
- var dev2 = Singleton.getInstance();
- console.log("Are you both Ibrahim Ersoy? " + (dev1 === dev2));
Why should you use it?
It's easy to use and lets you access global variables, and it's used by most modern JS Libraries out there.

Vignesh ManiPosted May 30, 2016, 9:29 AM
Nice one
Thiruppathi RPosted May 30, 2016, 1:40 AM
Easiest methods to understand..
Debasis SahaPosted May 30, 2016, 1:14 AM
Nice share..