DIV CSS 佈局教程網

深入理解 JavaScript:該避免的六種物件繼承寫法
編輯:關於JavaScript     

任何程式開發都離不開程式碼重複利用,否則每寫一個新功能都要從零開始。但重用的方式有好有壞。接下來兩篇文章將針對「繼承與重複利用」做討論:本篇是避免篇,談六種雖然能跑、卻各自帶著明顯缺陷的繼承寫法;下一篇則是推薦篇,介紹實務上更值得採用的模式。

模式一:最直覺的默認寫法

這是多數人直覺會寫出的形式:用 Parent() 的建構函式建立一個物件,再把該物件指派給 Child() 的原型。

function inherit(C, P) {
    C.prototype = new P();
}

// 父構造函數
function Parent(name) {
    this.name = name || 'Adam';
}
// 給原型添加say功能
Parent.prototype.say = function () {
    return this.name;
};
// Child構造函數為空
function Child(name) {
}

// 執行繼承
inherit(Child, Parent);

var kid = new Child();
console.log(kid.say()); // "Adam"

var kiddo = new Child();
kiddo.name = "Patrick";
console.log(kiddo.say()); // "Patrick"

// 缺點:不能讓參數傳進給Child構造函數
var s = new Child('Seth');
console.log(s.say()); // "Adam"

問題一針見血:Child 完全無法把參數往父建構函式傳遞, constructor 幾乎等於報廢。

模式二:借用建構函式

改讓 Child 借用 Parent 的建構函式,透過 apply 把 Child 的 this 與參數一併送進去:

// 父構造函數
function Parent(name) {
    this.name = name || 'Adam';
}

// 給原型添加say功能
Parent.prototype.say = function () {
    return this.name;
};

// Child構造函數
function Child(name) {
    Parent.apply(this, arguments);
}

var kid = new Child("Patrick");
console.log(kid.name); // "Patrick"

// 缺點:沒有從構造函數上繼承say方法
console.log(typeof kid.say); // "undefined"

參數問題解決了,但原型上的方法完全沒有被繼承過來,say 直接變成 undefined。

模式三:借用建構函式並設定原型

把前兩招合起來試試:

// 父構造函數
function Parent(name) {
    this.name = name || 'Adam';
}

// 給原型添加say功能
Parent.prototype.say = function () {
    return this.name;
};

// Child構造函數
function Child(name) {
    Parent.apply(this, arguments);
}

Child.prototype = new Parent();

var kid = new Child("Patrick");
console.log(kid.name); // "Patrick"
console.log(typeof kid.say); // function
console.log(kid.say()); // Patrick
console.dir(kid);
delete kid.name;
console.log(kid.say()); // "Adam"

功能上一切正常,但仔細看會發現 Parent 建構函式被執行了兩次——一次在 Parent.apply,一次在 new Parent()。程式能跑,效率卻很低。而且 delete kid.name 之後又變回 "Adam",也說明原型上殘留了一份不必要的父層实例屬性。

模式四:共享原型

讓 Child 與 Parent 直接共用同一個原型物件:

function inherit(C, P) {
    C.prototype = P.prototype;
}

// 父構造函數
function Parent(name) {
    this.name = name || 'Adam';
}

// 給原型添加say功能
Parent.prototype.say = function () {
    return this.name;
};

// Child構造函數
function Child(name) {
}

inherit(Child, Parent);

var kid = new Child('Patrick');
console.log(kid.name); // undefined
console.log(typeof kid.say); // function
kid.name = 'Patrick';
console.log(kid.say()); // Patrick
console.dir(kid);

參數依舊沒被正確接收。更麻煩的是,此後對 Child.prototype 的任何修改都會直接污染 Parent.prototype,反之亦然——這種綁死是實務上最難排查的問題之一。

模式五:臨時建構函式

這個寫法明顯成熟許多:先借用建構函式,再把 Child 的原型設為一個「臨時空建構函式」的實例,最後把 constructor 指標修回來。

/* 閉包 */
var inherit = (function () {
    var F = function () {
    };
    return function (C, P) {
        F.prototype = P.prototype;
        C.prototype = new F();
        C.uber = P.prototype;
        C.prototype.constructor = C;
    }
} ());

function Parent(name) {
    this.name = name || 'Adam';
}

// 給原型添加say功能
Parent.prototype.say = function () {
    return this.name;
};

// Child構造函數
function Child(name) {
}

inherit(Child, Parent);

var kid = new Child();
console.log(kid.name); // undefined
console.log(typeof kid.say); // function
kid.name = 'Patrick';
console.log(kid.say()); // Patrick
var kid2 = new Child("Tom");
console.log(kid.say()); 
console.log(kid.constructor.name); // Child
console.log(kid.constructor === Parent); // false

空的 F 建構函式讓父建構函式不必被執行,同時原型鏈依然連通,constructor 也被正確修正。剩下的問題還是老樣子:Child 依然無法把參數傳進父層。

模式六:klass 語法糖

最後這個模式試圖把整套繼承機制包成一個類似其他語言 class 的介面:

var klass = function (Parent, props) {

    var Child, F, i;

    // 1.
    // 新構造函數
    Child = function () {
        if (Child.uber && Child.uber.hasOwnProperty("__construct")) {
             Child.uber.__construct.apply(this, arguments);
        }
        if (Child.prototype.hasOwnProperty("__construct")) {
             Child.prototype.__construct.apply(this, arguments);
        }
    };

    // 2.
    // 繼承
    Parent = Parent || Object;
    F = function () {
    };
    F.prototype = Parent.prototype;
    Child.prototype = new F();
    Child.uber = Parent.prototype;
    Child.prototype.constructor = Child;

    // 3.
    // 添加實現方法
    for (i in props) {
        if (props.hasOwnProperty(i)) {
                Child.prototype[i] = props[i];
        }
    }

    // return the "class"
    return Child;
};

var Man = klass(null, {
    __construct: function (what) {
        console.log("Man's constructor");
        this.name = what;
    },
    getName: function () {
        return this.name;
    }
});

var first = new Man('Adam'); // logs "Man's constructor"
first.getName(); // "Adam"

var SuperMan = klass(Man, {
    __construct: function (what) {
        console.log("SuperMan's constructor");
    },
    getName: function () {
        var name = SuperMan.uber.getName.call(this);
        return "I am " + name;
    }
});

var clark = new SuperMan('Clark Kent');
clark.getName(); // "I am Clark Kent"

console.log(clark instanceof Man); // true
console.log(clark instanceof SuperMan); // true

功能上它確實把問題都解決了:參數正常傳遞、原型方法正常繼承、還提供了 uber 這個指向父原型的入口來呼叫父層方法。但代價是把語法與慣例擰成了另一個語言的樣子。在今天的專案裡,若非維護老程式,通常不值得為此增加一層認知負擔。

總結

以上六個模式都在某種特殊情境下實現了部分功能,卻各自帶著明顯缺陷:有的傳不了參數,有的繼承不到原型方法,有的讓父建構函式重複執行,有的會讓父子原型互相污染。因此在一般情況下,應盡量避免採用。

下一篇我們會談「推薦篇」,介紹在實務上更可靠、副作用更少的重複利用寫法。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved