单例模式的核心是确保只有一个实例,并提供全局访问。
var Singleton = (function () {
var instance;
function ClassDemo() {
this.name = "class demo";
}
ClassDemo.prototype.log = function () {
console.log(this.name);
};
return {
getInstance: function () {
if (!instance) {
instance = new ClassDemo();
}
return instance;
},
};
})();
var a = Singleton.getInstance();