单例无外乎每次调用返回的都是同一个对象,可以利用闭包实现
function Singleton(){ this.data = "singleton"; } Singleton.getInstance = (function(){ var instance; return function(){ instance = instance ? instance:new Singleton; return instance; } })(); var sa = Singleton.getInstance(); var sb = Singleton.getInstance(); console.log(sa === sb); console.log(sa.data);
输出结果
这种方式比较简单,Singleton类暴露全局,直接使用Singleton.getInstance()即可。
还有种情况,假设不想暴露Singleton,可以
var SingletonA = (function(){ var instance = null; function Singleton(){ this.init(); } Singleton.prototype.init = function(){ this.data = "SingletonA"; } return function(){ if(instance == null){ instance = new Singleton(); } return instance; }; })(); var b = SingletonA(); var c = SingletonA(); console.log(b === c); console.log(b.data);
输出
还有一种
var SingletonF = function(){ if(SingletonF.instance){ console.log("不能new"); } this.name = "gggg"; }; SingletonF.getInstance = function(name){ if(SingletonF.instance == null){ SingletonF.instance = new SingletonF(); } return SingletonF.instance; } var s1 = SingletonF.getInstance("ccc"); var s2 = SingletonF.getInstance("def"); console.log(s1 === s2); console.log(s1.name);
写法基本上大同小异,只要保证instance唯一就行了