1、利用IIFE只执行一次的机制实现
var Person = (function(){
var instance = null;
return function(name,age){
this.name = name;
this.age = age;
if(instance){
return instance
}
return instance = this
}
})()
Person.prototype.sayHello = function(){
console.log(this.name);
}
var xiaoming = new Person("小明",45);
var xiaohong = new Person("小红",25);
console.log(xiaoming)
console.log(xiaohong)
xiaoming.sayHello()
xiaohong.sayHello()
2、不改变单例模式,只实现单例机制,可设置一个代理类来实现单例模式
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.sayHello = function(){
console.log(this.name);
}
var PeopleProxy = (function(){
var instance = null;
return function(name,age){
if(instance){
return instance;
}
return instance = new Person(name,age);
}
})()
var xiaoming = new PeopleProxy("小明",26);
var xiaohong = new PeopleProxy("小红",20);
console.log(xiaoming);
console.log(xiaohong);
xiaoming.sayHello()
xiaohong.sayHello()