以下透過原型繼承實作類別的父子關係,並示範私有成員、方法重寫與呼叫父類同名方法的技巧。
// 使用原型繼承:中間以臨時物件作為 Child 的原型屬性,
// 臨時物件原型再指向父類原型,避免所有子類與父類共用同一個原型物件。
// 如此一來,修改子類原型時不會影響其他子類與父類。
function extend(Child, Parent) {
var F = function () {};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
Child.base = Parent.prototype;
}
function Parent(name) {
this.aa = 123;
this.getName = function () { return name; }; // 以閉包模擬私有成員
this.setName = function (value) { name = value; };
}
Parent.prototype.print = function () { alert("print!"); };
Parent.prototype.hello = function () {
alert(this.getName() + "Parent");
};
function Child(name, age) {
Parent.apply(this, arguments); // 呼叫父類建構式以繼承父類屬性
this.age = age;
}
extend(Child, Parent); // 繼承 Parent
Child.prototype.hello = function () { // 重寫父類的 hello
alert(this.getName() + "Child");
Parent.prototype.hello.apply(this, arguments); // 呼叫父類同名方法
};
// 子類自己的方法
Child.prototype.doSomething = function () { alert(this.age + "Child doSomething"); };
var p1 = new Child("xhan", 22);
var p2 = new Child("xxx", 33);
p1.hello();
p2.hello();
p1.doSomething(); // 子類方法
p1.print(); // 父類方法
alert(p1 instanceof Child); // true
alert(p1 instanceof Parent); // true
關鍵在於那個臨時建構式 F:它讓子類原型與父類原型之間隔了一層,既建立了原型鏈,又不會污染父類原型。搭配 Parent.apply(this, arguments) 繼承實例屬性,再透過 apply 呼叫父類方法,就組出相當完整的類繼承模型。