什麼是繼承?白話說,就是把別人現有的東西拿來用。要用得好,就得先弄清楚建構函數、物件、原型鏈這幾個概念。
JavaScript 裡常見的繼承方式有兩大類:
// 要被繼承的物件
var parent = {
name : "baba",
say : function(){
alert("I am baba");
}
}
// 新物件
var child = proInherit(parent);
// 測試
alert(child.name); // "baba"
child.say(); // "I am baba"
關鍵在 proInherit(obj) 這個方法。傳入一個物件,就能得到繼承了它全部屬性與方法的新物件。它不是內建方法,得自己定義,而且非常短:
function proInherit(obj) {
function F() {}
F.prototype = obj;
return new F();
}
其中 F() 是一個臨時的空建構函數。把它的 prototype 設為父物件後,透過 __proto__ 鏈的串接,新物件就受益而擁有了父物件的全部能力。
鏈式結構如下:

// 父類建構函數
function Parent() {
this.name = "baba";
}
// 父類原型方法
Parent.prototype.getName = function () {
return this.name;
}
// 子類建構函數
function Child() {
this.name = "cc";
}
// 類式繼承
classInherit(Parent, Child);
// 實例
var child = new Child();
alert(child.getName()); // "baba"
關鍵方法是 classInherit(Parent, Child):
var classInherit = (function () {
var F = function () { }
return function (P, C) {
F.prototype = P.prototype;
C.prototype = new F();
C.prototype.constructor = C;
}
}());
拆解一下:
F(),用它的實例透過 __proto__ 屬性把父類與子類的原型鏈接起來。它扮演代理的角色,目的是避免直接寫 C.prototype = P.prototype——那樣一來,子類實例在修改屬性時會連父類一起改到。F(),這樣多次繼承時不必反覆建立大量空建構函數,能省下記憶體。C 的實例的 constructor 會指向 P,所以要手動改回來。鏈式結構如下:

這種方式能繼承原型方法,但父類在建構函數中定義的實例屬性無法繼承。為了解決這點,可以再搭配複製繼承。
// 複製繼承
function copyInherit(p, c) {
var i,
toStr = Object.prototype.toString,
astr = "[object Array]";
c = c || {};
for (i in p) {
if (p.hasOwnProperty(i)) {
if (typeof p[i] === "object") {
c[i] = toStr.call(p[i]) == astr ? [] : {};
c[i] = copy(p[i], c[i]);
} else {
c[i] = p[i];
}
}
}
return c;
}
// 重寫 Parent
function Parent() {
this.name = "pp";
this.obj = {a: 1, b: 2};
this.arr = [1, 2];
}
// 實例
var child = new Child();
var parent = new Parent();
copyInherit(parent, child);
alert(child.name); // "baba"
alert(child.arr); // 1,2
alert(child.obj.a); // 1
分析一下 copyInherit(p, c):賦值分傳值與傳參考兩種。當父物件的屬性包含陣列或物件時,c[i] = toStr.call(p[i]) == astr ? [] : {} 這一句先幫子物件建立一個全新的容器,這樣後續修改子物件的屬性時,才不會連帶把父物件的屬性竄改掉。
類式繼承最普遍,因為大家都熟悉建構函數的寫法,缺點是記憶體占用較大。原型式繼承省記憶體,但遇到陣列或物件類型的屬性時,克隆起來比較麻煩。複製繼承寫法簡單、應用面廣,可以作為前兩者的補充。
在真實專案中,這幾種方式往往不是二選一,而是依場景混用:方法放原型鏈上共享,實例屬性則靠複製或建構函數呼叫來帶過去。