单例模式是什么?
  单例就是保证一个类只有一个实例,实现方法一般是先判断实例存在与否,如果存在直接返回,如果不存在就创建了再返回,这就确保了一个类只有一个实例对象。在JavaScript里,单例作为一个命名空间提供者,从全局命名空间里提供一个唯一的访问点来访问该对象。
代码
单例模式的简单实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| function Window(name) { this.name = name; } Window.prototype.getName = function () { return this.name; }
Window.getInstance = (function () { let instance; return function (name) { if (!instance) { instance = new Window(name); } return instance; } })();
let w1 = Window.getInstance(); let w2 = Window.getInstance();
console.log(w1 === w2)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| class Window { constructor(name) { this.name = name; } static getInstance() { if (!this.instance) { this.instance = new Window(); } return this.instance; } } let w1 = Window.getInstance(); let w2 = Window.getInstance(); console.log(w1 === w2)
|