在物件導向中,子類別通常需要呼叫父類別的方法。JavaScript 沒有像部分語言一樣的 super 關鍵字,但可以透過原型與額外屬性建立類似的機制。
可以為子類別的建構函式加入一個 uber 屬性,讓它指向父類別的原型。這樣物件在呼叫同名方法時,就能沿著原型鏈往上查找。
function Parent() {}
Parent.prototype.name = "Anna";
Parent.prototype.toString = function () {
return this.name;
};
function Child() {}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
Child.uber = Parent.prototype;
Child.prototype.name = "Jock";
Child.prototype.toString = function () {
var parent = this.constructor.uber;
return parent ? parent.toString.call(this) + ", " + this.name : this.name;
};
當子物件呼叫 toString() 時,會先透過建構函式上的 uber 取得父類別原型,再呼叫父類別方法並串接目前物件名稱。
這種做法能清楚表達原型繼承關係,也方便在子類別中重用父類別邏輯。