JavaScript 沒有 class 關鍵字(ES6 之前),繼承得靠原型鏈與函數呼叫手工實作。以下整理三種常見寫法,並說明各自的取捨。
// 父類
function person() {
this.hair = 'black';
this.eye = 'black';
this.skin = 'yellow';
this.view = function () {
return this.hair + ',' + this.eye + ',' + this.skin;
};
}
// 子類
function man() {
this.feature = ['beard', 'strong'];
}
man.prototype = new person();
var one = new man();
console.log(one.feature); // ['beard','strong']
console.log(one.hair); // black
console.log(one.view()); // black,black,yellow
寫法很簡單:把子類的 prototype 指向父類的一個實例,之後子類實例就能沿著原型鏈找到父類的方法。
prototype 到底是什麼?每個函數被定義時都有一個 prototype 屬性,它是個物件,用來實作「向上攀查」:當某屬性在當前物件找不到時,就沿著原型鏈一層層往上找,直到找到為止,或直到 __proto__ 為 null。
以 one.view() 為例:one 自身沒有 view,於是查 man.prototype,而它是 person 的實例、上面有 view,於是呼叫成功。
function person() {
this.hair = 'black';
this.eye = 'black';
this.skin = 'yellow';
this.view = function () {
return this.hair + ',' + this.eye + ',' + this.skin;
};
}
function man() {
person.apply(this, []); // 注意:空參數要傳 [] 或 new Array()
this.feature = ['beard', 'strong'];
}
var one = new man();
console.log(one.view()); // black,black,yellow
用 apply 把父類的屬性「複製」到子類的 this 上。要注意若沒有參數要傳,必須給空陣列,傳 null 是無效的。
function man() {
person.call(this, []);
this.feature = ['beard', 'strong'];
}
man.prototype = new person();
var one = new man();
console.log(one.view()); // black,black,yellow
為什麼要多加 man.prototype = new person()?因為 call 只完成了「屬性複製」,並沒有建立原型鏈上的方法繼承。兩者搭配才能同時拿到屬性與原型方法。Google Maps API 就是採這種繼承方式。
假設父類需要建構參數:
function person(hair, eye, skin) {
this.hair = hair;
this.eye = eye;
this.skin = skin;
this.view = function () {
return this.hair + ',' + this.eye + ',' + this.skin;
};
}
這時 prototype 純繼承就不適用了,因為無法把參數傳進父類。必須改用 apply 或 call:
// apply 版
function man(hair, eye, skin) {
person.apply(this, [hair, eye, skin]);
this.feature = ['beard', 'strong'];
}
// call 版
function man(hair, eye, skin) {
person.call(this, hair, eye, skin);
this.feature = ['beard', 'strong'];
}
但 apply/call 有個致命問題:它沒有建立原型鏈,因此 instanceof 會失效——one instanceof person 回傳 false,即使 one 明明拿到了 person 的所有屬性。
function Person(name) {
this.name = name;
}
Person.prototype.getName = function () {
return this.name;
};
function Chinese(name, nation) {
Person.call(this, name); // 借用建構式拿到實例屬性
this.nation = nation;
}
// 以空函數中繼建立原型鏈,避免執行一次父類建構式
function inherit(subClass, superClass) {
function F() {}
F.prototype = superClass.prototype;
subClass.prototype = new F();
subClass.prototype.constructor = subClass.constructor;
}
inherit(Chinese, Person);
Chinese.prototype.getNation = function () {
return this.nation;
};
var p = new Person('shijun');
var c = new Chinese("liyatang", "China");
console.log(c instanceof Chinese); // true
console.log(c instanceof Person); // true
這種「寄生組合式繼承」結合了兩種策略的優點:用 call 借用建構式取得每個實例獨立的屬性,用中繼函數 F 建立原型鏈而不必真的執行一次父類建構式,同時 instanceof 也能正確運作。
補充一點:範例中的 subClass.prototype.constructor = subClass.constructor 其實是個筆誤,正確寫法應該是 subClass.prototype.constructor = subClass,否則 constructor 仍會指回父類。ES6 的 class extends 語法糖背後做的就是這套機制,只是把細節都封好了。