JavaScript 的繼承一直是最容易混淆的主題之一,因為它有多種寫法,而且每種都有各自的副作用。這篇把常見的幾種模式並排列出,說明它們各自的問題在哪裡。
先從一個不會產生多餘屬性與方法的做法開始:
/**
* 讓子類繼承父類,但不會產生多餘的屬性和方法
* @returns {Function}
*/
define(function () {
return function (subType, superType) {
var proto = new Object(superType.prototype);
proto.constructor = subType;
subType.prototype = proto;
};
});
父類的建構函式:
define(function () {
function ostring(s) {
this.str = s;
this.length = this.str.length;
}
ostring.prototype.show = function () {
alert(this.str);
};
return ostring;
});
子類的定義,用 call 呼叫父類建構子,再用上面的工具函式繼承原型:
define(['inherit', 'ostring'], function (inherit, ostring) {
function wstring(s) {
// 用 call 呼叫父類建構函式
ostring.call(this, s);
this.chlength = 2 * s.length;
}
// 繼承父類的其他屬性與方法
inherit(wstring, ostring);
wstring.prototype.add = function (w) {
alert(this.str + w);
};
return wstring;
});
function Person(name) {
this.name = name;
}
Person.prototype.getName = function () {
return this.name;
}
function Author(name, books) {
this.inherit = person;
this.inherit(name);
this.books = books;
}
var au = new Author("dororo", "Learn much");
au.name;
等效的簡潔寫法是直接用 call:
function Author(name, books) {
Person.call(this, name);
this.books = books;
}
var au = new Author("dororo", "Learn much");
au.getName;
致命缺點:只能繼承建構函式裡用 this 設立的屬性,prototype 上的方法完全繼承不到。因為 Person.call(this, name) 只是把 this 換成 Author 的 this 再執行一次 Person,而 getName 掛在 Person 的原型上,跟這次呼叫無關。所以上面 au.getName 是 undefined。
另外有個順序陷阱:子類必須在定義自己的屬性之前呼叫父類建構子,否則自己的屬性會被父類覆蓋。也就是說 this.books 一定要寫在 Person.call() 之後。同理,子類也不宜用 prototype 定義自己的方法——實例化時 prototype 先執行、父類建構子後執行,容易被蓋掉。
function Person(name) {
this.name = name;
}
Person.prototype.getName = function () {
return this.name;
}
function Author(name, books) {
this.books = books;
}
Author.prototype = new Person(name);
Author.prototype.constructor = Author;
Author.prototype.getBooks = function () {
return this.books;
}
var au1 = new Author("dororo1", "Learn much");
var au2 = new Author("dororo2", "Learn less");
alert(au1.getName());
alert(au2.getName());
這個做法解決了 prototype 無法繼承的問題,因為 new Person() 會把 Person 的建構內容與原型屬性一起納入。
但缺點同樣明顯:Author.prototype 已經被實例化了。原型上的屬性對所有子類實例是共享的參考,所以範例裡 au1 與 au2 的 name 都會是最後一次賦值的結果。此外範例中 new Person(name) 的 name 是未定義的變數,會丟出錯誤——這段程式碼本身也示範了「直接在原型上實例化」是多麼容易出錯。
function Person(name) {
this.name = name;
}
Person.prototype.getName = function () {
return this.name;
}
function Author(name, books) {
this.base = new Person(name);
for (var key in this.base) {
if (!this[key]) {
this[key] = this.base[key];
}
}
this.book = books;
}
var au1 = new Author("dororo1", "work");
var au2 = new Author("dororo2", "play");
alert(au1.getName());
alert(au2.getName());
這屬於擴充式做法:把父類的所有屬性都拷貝到子類身上。上述兩方面的問題都沒有了,每個實例各自獨立。缺點是效率較差(每個實例都要建立一個父類物件再遍歷拷貝),而且原型鏈上的方法能不能被 for...in 撈到,取決於屬性的 enumerable 設定。
把上面幾段串起來,會發現 JS 的繼承其實分成兩個獨立問題,各用不同手段解決。
屬性的繼承靠改變函式的執行環境來達成,工具是 call() 與 apply():
function Animal(typeName) {
// 為當前的執行環境(this)加上屬性
this.typeName = typeName;
this.colors = ["red", "white"];
}
// 在原型上加入方法
Animal.prototype.Shout = function () { alert("我是:--" + this.typeName); };
Animal.prototype.Eat = function () { alert("我是:--" + this.typeName); };
function Lion(tn) {
// 用 apply 的第一個參數把 Animal 的執行環境改成 Lion 的 this
Animal.apply(this, ["獅子"]);
}
Lion.prototype = Animal.prototype; // 繼承方法——但這寫法有問題
Lion.prototype.Hunt = function () {
alert("我是:獅子,我要去捕獵");
}
var aminm = new Animal();
aminm.Hunt(); // 父類居然能呼叫子類的方法,顯然不對
問題出在 Lion.prototype = Animal.prototype 讓兩者指向同一個物件,子類新增方法等於污染父類。修正方式是讓子類原型指向父類的一個「新實例」:
Lion.prototype = new Animal(); // 繼承父類方法 var lion = new Lion(); lion.Shout(); lion.Eat();
上面這段程式之所以能運作,靠的是 new 悄悄完成的四件事:
this 指向這個新物件。換句話說,new Lion() 之後,Lion 函式裡的 this 就是 Lion 物件本身。
父類建構函式被呼叫了兩次。Animal.apply(this, ...) 呼叫一次,Lion.prototype = new Animal() 又呼叫一次。若父類建構子有副作用或成本較高,這就是浪費。
標準解法是建立一個中間的空函式搭橋,只借原型、不執行建構內容——這正是本文開頭那個 inherit 工具函式在做的事,也是 Object.create() 的實作原理:
Lion.prototype = Object.create(Animal.prototype); Lion.prototype.constructor = Lion;
把這幾種寫法放在一起看,結論其實很清楚:屬性用 call 帶過去,方法用原型鏈接過去,兩者搭配使用。這就是所謂的「寄生組合式繼承」,也是 ES6 之前公認最完整的方案。ES6 的 class 與 extends 只是把這套機制包上了更清楚的語法,底層跑的仍然是原型鏈。