一个类只允许创建一个实例,这个类就是单例类,这种模式就是单例模式。
弹窗,无论点击多少次,弹窗只应该被创建一次。
js
// 函数代理
function Person(name) {
this.name = name;
}
var ProxyModel = (function() {
var instance;
return (function(name) {
return instance || instance = new Person(name);
})
})()
var a = new ProxyModel('李雷');
console.log(a.name); // 李雷
var b = new ProxyModel('张飞');
console.log(b.name); // 李雷
// es6 类
class Person {
constructor(name) {
this.name = name;
if(Person.instance) {
return Person.instance;
}
Person.instance = this;
return this;
}
}
const a = new Person('李雷');
console.log(a.name); // 李雷
const b = new Person('张飞');
console.log(b.name); // 李雷