Skip to content

Instantly share code, notes, and snippets.

@bmino
Last active June 26, 2018 22:56
Show Gist options
  • Save bmino/a52998e6c184437ac0e524cf8ff06daa to your computer and use it in GitHub Desktop.
Save bmino/a52998e6c184437ac0e524cf8ff06daa to your computer and use it in GitHub Desktop.
Create Instances and Singletons
let api = function Binance() {
let self = this;
self.cache = 0;
return {
setCache: function(val) {
self.cache = val;
},
getCache: function() {
return self.cache;
}
};
};
module.exports = api;
const api = require('./ModuleExample');
const api2 = require('./ModuleExample');
let singleton1 = api();
let singleton2 = api2();
let instance1 = new api();
let instance2= new api();
// Set value of singleton
singleton1.setCache('this can be overridden');
// Set other value of the same singleton even though it was created somewhere else
singleton2.setCache('see I overrode the previous value');
// Set value of instance
instance1.setCache('other stuff');
// Set value of another separate instance
instance2.setCache('different stuff');
console.log(singleton1.getCache()); //see I overrode the previous value
console.log(singleton2.getCache()); //see I overrode the previous value
console.log(instance1.getCache()); //other stuff
console.log(instance2.getCache()); //different stuff
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment