Two scenarios for the js singleton pattern
- 2020-03-26 21:33:26
- OfStack
Scenario 1: you can flexibly read internal variables by taking advantage of the two functions of closures, and you can keep them in memory.
//Plan a
var SingletonTester = (function () {
//Singleton method
function Singleton(args) {
var args = args || {};
this.name = 'SingletonTester'; //The other way is to return an object
this.pointX = args.pointX || 6;
this.pointY = args.pointY || 10;
}
//The singleton instance
var instance;
//Returns the object
return {
name: 'SingletonTester',
getInstance: function (args) {
if (instance === undefined) {
instance = new Singleton(args);
}
return instance;
}
};
})(); //Execute the method directly
// test
var test = SingletonTester.getInstance({ pointX: 5 });
console.log(test.pointX);
Scheme 2:
//Scheme 2
function Universe() {
//Determine if an instance exists
if (typeof Universe.instance === 'object') {
return Universe.instance;
}
//Other content
this.start_time = 0;
this.bang = "Big";
// The cache
Universe.instance = this;
//Implicitly returns this
}
// test
var uni = new Universe();
var uni2 = new Universe();
console.log(uni === uni2); // true