单例模式
箭头函数写法
const singleton = function () { };
singleton.getInstance = (() => {
let instance = null;
return () => {
if (!instance) {
instance = new singleton();
}
return instance;
}
})()
const s1 = singleton.getInstance();
const s2 = singleton.getInstance();
console.log(s1 === s2);//truefunction写法
singleton.getInstance=(function(){
let instance = null;
return function(){
if(!instance){
instance = new singleton();
}
return instance;
}
})();
const s1 = singleton.getInstance();
const s2 = singleton.getInstance();
console.log(s1===s2);class写法
实例1
实例2
Last updated
Was this helpful?