Created
September 14, 2017 05:44
-
-
Save dsxsxsxs/802ae2e78f8d7c0719eb9e4d8025859b to your computer and use it in GitHub Desktop.
Singleton pattern with JS ES5 and ES6
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Singleton() { | |
if (!(this instanceof Singleton)) | |
return new Singleton; | |
if (Singleton.hasOwnProperty('singleton')) | |
return Singleton.singleton; | |
Object.defineProperty(Singleton, 'singleton',{ | |
value: this, | |
enumerable:false, | |
writable:false, | |
configurable:false | |
}); | |
} | |
var instance1 = Singleton(), instance2 = new Singleton, instance3 = new Singleton; | |
console.log(instance1 == instance2); // true | |
console.log(instance2 == instance3); // true | |
console.log(instance1 == Singleton.singleton); // true | |
console.log(instance2 == Singleton.singleton); // true | |
console.log(instance3 == Singleton.singleton); // true | |
//es6 | |
class Singleton{ | |
constructor() { | |
if (Singleton.hasOwnProperty('singleton')) | |
return Singleton.singleton; | |
Object.defineProperty(Singleton, 'singleton',{ | |
value: this, | |
enumerable:false, | |
writable:false, | |
configurable:false | |
}); | |
} | |
} | |
const instance1 = new Singleton, instance2 = new Singleton; | |
console.log(instance1 == instance2); // true | |
console.log(instance1 == Singleton.singleton); // true | |
console.log(instance2 == Singleton.singleton); // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment