單例模式

function A() {
    // 實例對象
    var instance;
    // 新的構造函數
    B = function () {
        // 返回這個實例對象
        return instance;
    };
    // 原型鏈繼承
    B.prototype = this; // this是一個A的實例對象
    B.prototype.constructor = B;
    instance = new B();

    // A的私有屬性
    var a = 1;
    // 特權函數
    instance.log = function () {
        console.log(a);
    };
    // 此處相當於經典繼承
    instance.name = "name";
    return instance;
}

let a = new A();
let b = new B();
console.log(b === a);
a.log();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章