DIV CSS 佈局教程網

JavaScript 繼承實作整理:從原型到 apply 綁定
編輯:JavaScript基礎知識     

做前端之前我寫得比較多的是 .NET 與 PHP,早期用 JS 總喜歡直接抓個庫來用。幾次實踐證明,不懂原理連改程式碼都改不好,於是下定決心把 JavaScript 的幾個技術難點補起來。這篇就整理繼承的實作方式。

0x1. 物件與建構函數

最直覺的物件定義方式:

var a = {
  x: 1,
  y: 2,
  add: function () { return this.x + this.y; },
  mul: function () { return this.x * this.y; }
}

這樣就得到一個帶有 x、y 兩個公有成員和 add、mul 兩個公有方法的變數。但這種定義方式有兩個明顯缺點:

1、批量建立物件很不方便。若寫 var b = a;,由於 JS 的引用機制,改動 b 的成員會同時改掉 a 的;

2、每次建立物件若需要自訂成員,都得重寫一遍賦值操作,程式碼行數膨脹。

因此在定義物件之前,我們可以先定義一個建構函數:

function A(x, y) {
  this.x = x;
  this.y = y;
  this.add = function () { return this.x + this.y; }
  this.mul = function () { return this.x * this.y; }
}

然後建立物件:

a = new A(1, 2);

這句話看起來簡單,但要和 C++ 這類語言區分開:A 並不是嚴格意義上的「類」,因為 JavaScript 根本沒有類,這裡只是呼叫了建構函數而已。

問題來了:怎麼實現繼承?C++ 把封裝、繼承、多型三個特性落實得清清楚楚,而 JavaScript 沒有嚴格的繼承機制,只能用幾種方式來模擬。

0x2. prototype

prototype 是只有 Function 才有的屬性。設計繼承的目的無非是「把公共部分提取出來」以實現程式碼復用,而在 JS 中,公共部分就放在 Function 的 prototype 上。

寫法一:子類原型指向父類物件

function A(x, y) {
  this.x = x;
  this.y = y;
  this.add = function () { return this.x + this.y; }
  this.mul = function () { return this.x * this.y; }
}
function B(x, y) {}
B.prototype = new A(1, 2);
console.log(new B(3, 4).add()); // 3

這個例子中,子類的 prototype 指向一個 A 類物件。

寫法二:子類原型引用父類原型

function A() {}
A.prototype = {
  x: 1,
  y: 2,
  add: function () { return this.x + this.y; },
  mul: function () { return this.x * this.y; }
}
A.prototype.constructor = A;

function B() {}
B.prototype = A.prototype;
B.prototype.constructor = B;

此時 B 的 prototype 物件引用了 A 的 prototype。既然是引用,那麼改動 B.prototype 也會連帶改動 A.prototype,因為本質上它們指向同一塊記憶體。所以每次改動 B 的原型,都要手動把 constructor 改回來,否則容易錯亂。相比之下,寫法一因為是新建物件而非共享引用,不會有這個問題。

建立 B 類型的物件:

b = new B();

它擁有 A 類型的一切成員:

console.log(b.add()); // 3

原理在於每個 prototype 物件都有兩個重要成員:constructor 與 __proto__。constructor 本質上是一個函數指標,執行 B.prototype = A.prototype 後它會被覆蓋掉,所以後面必須讓 constructor 重新指向 B 的建構函數。

0x3. 建構函數綁定

定義完 A 之後,再定義 B,並在 B 的建構函數內部「嵌入執行」A 的建構函數:

function A(x, y) {
  this.x = x;
  this.y = y;
  this.add = function () { return this.x + this.y; }
  this.mul = function () { return this.x * this.y; }
}
function B(x, y, z) {
  A.apply(this, arguments);
  this.z = z;
}
console.log(new B(1, 2, 3));

apply 和 call 基本上一樣,可以在 B 的建構函數內部執行 A 的建構函數,同時繼承 A 的所有成員。

顯示結果:

這裡給個公式:在 B 的建構函數裡寫 A.apply(this, arguments),可以讓 B 建構出來的物件擁有 A 建構函數裡的所有成員。

談到 apply 與 call,還能實現多重繼承:

function IA() {
  this.walk = function () { console.log("walk"); }
}
function IB() {
  this.run = function () { console.log("run"); }
}
function Person() {
  IA.apply(this);
  IB.apply(this);
}
var p = new Person();
p.walk(); // walk
p.run();  // run

實務上最穩健的做法,是把兩者結合:用 A.call(this, ...) 繼承「每個物件各自擁有的屬性」,用原型鏈繼承「共享的方法」。這樣既避免引用互相污染,又能實現方法復用,也就是業界俗稱的組合式繼承。

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