JavaScript 沒有 class 關鍵字(ES6 之前),要讓子類沿用父類的屬性與方法,其中一種直覺做法是在子類建構函式中呼叫 apply,把 this 借給父類使用。原理是:apply 能改變函式內 this 的指向,於是父類寫在 this 上的屬性就長到了子物件身上。
<script type="text/javascript">
// 以 apply 實作物件繼承
function Parent(username) {
this.username = username;
this.sayHello = function() {
alert(this.username);
};
}
function Child(username, password) {
Parent.apply(this, new Array(username));
// 等價寫法:Parent.apply(this, [username]);
this.password = password;
this.sayWorld = function() {
alert(this.password);
};
}
var parent = new Parent("zhangsan");
var child = new Child("lisi", "123");
parent.sayHello(); // zhangsan
child.sayHello(); // lisi —— 沿用了父類的方法
child.sayWorld(); // 123 —— 子類自己的方法
</script>
兩者功能相同,只是參數傳遞形式不同:apply 收一個陣列,call 則把參數逐一列舉。寫成 Parent.call(this, username) 效果一模一樣,參數少的時候 call 讀起來更俐落。
apply 式繼承屬於「建構繼承」,父類的方法是在建構時指派到 this 上的,因此每 new 一個子物件就會重新產生一份函式,無法共用;而且父類prototype 上的方法完全不會被繼承。若要更完整的繼承鏈,通常會搭配 Child.prototype = new Parent() 或現代的 Object.create,並記得把 prototype.constructor 指回 Child。