Skip to content

Instantly share code, notes, and snippets.

@dhutaryan
Created June 7, 2018 16:31
Show Gist options
  • Save dhutaryan/21806f687a591745c43c916e6b204dba to your computer and use it in GitHub Desktop.
Save dhutaryan/21806f687a591745c43c916e6b204dba to your computer and use it in GitHub Desktop.
const singleton = (function() {
let instance;
function init() {
let count = 0;
return {
getValue,
increase
};
function getValue() {
return count;
}
function increase() {
return count += 1;
}
}
return {
getInstance() {
!instance && (instance = init());
return instance;
},
};
})();
var s = singleton.getInstance();
console.log(s.getValue()); // 0
console.log(s.increase()); // 1
var s2 = singleton.getInstance();
console.log(s2.getValue()); // 1
console.log(s2 === s); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment