function Person(name) {
this.name = name;
this.work()
}
Person.prototype.work = function() {
console.log(this.name + " is working");
}
var p1 = new Person("Darren"); //Darren is working
//p1.work();
var p2 = new Person("Jack"); //Jack is working
console.log(p1 === p2); //false
方法一,利用闭包,在生成某各对象时先判断是否存在。存在就不生成对象,不存在就生成对象。
var A = (function() {
var res
return function(name) {
if (!res) {
res = new B(name)
}
return res
}
})()
var B = function Person(name) {
this.name = name
this.work()
}
B.prototype.work = function() {
console.log(this.name + " is working");
}
var p1 = new A("Darren"); //Darren is working
var p2 = new A("Jack");
console.log(p1 === p2) //true
方法一中若想生成另一个单例,需要重写类似A的函数
var A = (function() {
var res
return function(name) {
if (!res) {
res = new B(name)
}
return res
}
})()
var C = (function() {
var res
return function(name) {
if (!res) {
res = new B(name)
}
return res
}
})()
var B = function Person(name) {
this.name = name
this.work()
}
B.prototype.work = function() {
console.log(this.name + " is working");
}
var p1 = new A("Darren"); //Darren is working
var p2 = new A("Jack");
var p3 = new C("Jack");//Jack is working
console.log(p1 === p2) //true
方法二 ,是对方法一的改进,减少了重复代码
var A = function(B) {
var res
return function() {
return res || (res = B.apply(this, arguments))
}
}
var B = function Person(name) {
this.name = name
this.work()
}
B.prototype.work = function() {
console.log(this.name + " is working");
}
var c = A((name) => new B(name))
var d = A((name) => new B(name))
var p1 = c("Darren"); //Darren is working
var p2 = c("Jack");
var p3 = d("Jack");//Jack is working
console.log(p1 === p2) //true