1、使用構造函數的默認屬性
function A(name){
// 如果已存在對應的實例
if(typeof A.instance === 'object'){
return A.instance
}
//否則正常創建實例
this.name = name
// 緩存
A.instance =this
return this
}
var a1 = new A()
var a2= new A()
console.log(a1 === a2)//true
2、借助閉包
var Head = (function () {
var HeadClass = function () { }; // 聲明HeadClass對象,無法在外部直接調用
var instance; // 聲明一個instance對象
return function () {
if (instance) { // 如果已存在 則返回instance
return instance;
}
instance = new HeadClass() // 如果不存在 則new一個
return instance;
}
})();
var a = Head();
var b = new Head();
console.log(a===b) // true
var a = HeadClass(); // 報錯,HeadClass is not defined
3、立即執行函數
var A;
(function(name){
var instance;
A = function(name){
if(instance){
return instance
}
//賦值給私有變量
instance = this
//自身屬性
this.name = name
}
}());
A.prototype.pro1 = "from protptype1"
var a1 = new A('a1')
A.prototype.pro2 = "from protptype2"
var a2 = new A('a2')
console.log(a1.name)
console.log(a1.pro1)//from protptype1
console.log(a1.pro2)//from protptype2
console.log(a2.pro1)//from protptype1
console.log(a2.pro2)//from protptype2
