DIV CSS 佈局教程網

以 prototype 在 JavaScript 中模擬物件導向繼承
編輯:關於JavaScript     

本文示範如何以 prototype 在 JavaScript 中實作近似 OOP 的繼承關係,供需要的朋友參考。

先釐清兩個前提

在這個模型裡有兩條規則值得先記住:以 this 修飾的公有屬性可以被子類覆蓋;以 var 修飾的私有屬性則不能被覆蓋。也就是說,子類無法存取父類的私有屬性,而父類自己的方法仍能正常讀取父類的私有變數——因為那些方法是在父類的作用域中被建立的。

程式碼

function Vegetable(){
    this.taste='delicious';
    var a = 'I\'m Vegetable\'a!'
    this.fun1 = function(){
        alert('Vegetable fun1 doing...');
    }
    this.fun3 = function(){
        alert(a);
    }
}

function Celery(){
    var a = 'I\'m Celery\' a';
    this.color = 'green';
    this.taste = 'bad';
    this.fun1a = function(){
        alert('Celeryfun1 doing...');
    }
    this.fun2 = function(){
        alert('Celery fun2 doing...');
    }
    this.fun4 = function(){
        alert(a);
    }
}

Celery.prototype = new Vegetable();

var stick = new Celery();
var polymorphed = stick.taste;
//alert(polymorphed);
//alert(stick.color);
//stick.fun1();
//stick.fun2();
//stick.fun3();
stick.fun4();

程式碼在示範什麼

Celery.prototype = new Vegetable() 這一行是繼承的關鍵:它讓所有 Celery 實例在原型鏈上連到一個 Vegetable 物件,因此 Vegetable 掛在 this 上的 taste 與 fun1 都成為 Celery 實例可用的成員。而 Celery 建構子自己又設了 taste 與 color,於是 taste 被覆蓋成 'bad',color 則是新增的。

私有變數 a 在兩個建構子中各有一份,互不干擾。stick.fun3() 若被執行,會讀到 Vegetable 的那份;stick.fun4() 讀到的是 Celery 的那份。由於 a 被閉包鎖在建構子內部,外部完全無法存取,這就是所謂的私有。

這個寫法的四個問題

第一,原型物件是共用而非複製。new Vegetable() 只執行一次,所有 Celery 實例共用同一個原型物件。若父類屬性中有參照型別(陣列、物件),一個實例改動會影響全部。

第二,父建構子沒被執行到每個實例。因此每個實例的父類初始化狀態其實是同一份,無法各自獨立。

第三,在建構子中定義方法效率差。每次 new 都會重新建立一份函數物件,與掛在 prototype 上的做法相比浪費記憶體。上面程式碼把方法寫在建構子裡,正是為了讓私有變數能被閉包捕獲而付出的代價。

第四,new Vegetable() 若父建構子需要參數就無法傳遞。

較現代的寫法

ES5 之後可用 Object.create 建立乾淨的原型鏈,避免呼叫父建構子:

function Celery() {
    Vegetable.call(this);   //把父類初始化套用到自己
    this.color = 'green';
    this.taste = 'bad';
}
Celery.prototype = Object.create(Vegetable.prototype);
Celery.prototype.constructor = Celery;  //補回 constructor 指向

而 ES6 的 class 語法只是原型繼承的語法糖,寫起來直觀得多:

class Vegetable {
    constructor() { this.taste = 'delicious'; }
    fun1() { console.log('Vegetable fun1'); }
}

class Celery extends Vegetable {
    constructor() {
        super();            //等同 Vegetable.call(this)
        this.color = 'green';
        this.taste = 'bad';
    }
    fun2() { console.log('Celery fun2'); }
}

需要留意的是,class 中宣告的方法預設掛在原型上,而 # 開頭的私有欄位才是真正語言層級的私有:

class Celery extends Vegetable {
    #secret = 'private';
    reveal() { return this.#secret; }
}

希望本文所述對你的 JavaScript 學習有所幫助。

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