//1. ES5 闭包实现单例模式
let singleton = (function(){
let instance = null;
return function(name){
this.name = name;
instance = instance? instance : this;
return instance;
}
})();
singleton.prototype.getName = function(){
return this.name;
}
let w = new singleton("hello");
console.log(w.getName());
let m = new singleton("nihao")
console.log(m.getName());
// 2. ES6 实现单例模式
class singleton {
constructor(name){
this.name = name;
}
static getInstance(name){
if(!this.instance){
this.instance = new singleton(name);
}
return this.instance;
}
}
let w = singleton.getInstance("hello");
console.log(w.name);
let m = singleton.getInstance("nihao")
console.log(m.name);