ES6 的 class 出現之前,JavaScript 的繼承要靠三種手法組合:原型鏈、構造函數借用、以及 call/apply。理解它們,才能真正看懂 class 語法糖底下發生了什麼。
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.sayHello = function () {
alert("使用原型得到 Name:" + this.name);
};
var per = new Person("馬小倩", 21);
per.sayHello(); // 使用原型得到 Name:馬小倩
function Student() {}
Student.prototype = new Person("洪如彤", 21); // 關鍵:把父類實例當成自己的原型
var stu = new Student();
Student.prototype.grade = 5;
Student.prototype.intr = function () { alert(this.grade); };
stu.sayHello(); // 使用原型得到 Name:洪如彤(繼承而來)
stu.intr(); // 5
原理是讓子類型的 prototype 指向一個父類型的實例,於是子實例透過原型鏈查找,能找到父原型上的方法。
致命缺點:父類的屬性會被所有子實例共享。若父類有 this.friends = [],所有子實例的 friends 會是同一個陣列,一個改了全部跟著改。這在實戰中幾乎必然出事。
function Parent(name) {
this.name = name;
this.sayParent = function () { alert("Parent:" + this.name); };
}
function Child(name, age) {
this.tempMethod = Parent;
this.tempMethod(name); // 借用父建構子,把 this 指向自己
this.age = age;
this.sayChild = function () {
alert("Child:" + this.name + " age:" + this.age);
};
}
var child = new Child("李鳴", 24);
child.sayChild(); // Child:李鳴 age:24
這樣每個子實例都有自己的屬性副本,解決了共享問題。缺點是方法也變成每個實例一份,無法共用,浪費記憶體;而且只能繼承實例屬性,拿不到父原型上的方法。
function Person(name, age, love) {
this.name = name; this.age = age; this.love = love;
this.say = function () { alert("姓名:" + name); };
}
function student(name, age) {
Person.call(this, name, age); // 逐一列參數
}
function teacher(name, love) {
Person.apply(this, [name, love]); // 參數放陣列
// Person.apply(this, arguments); // 等效寫法
}
new student("曹玉", 18).say(); // 曹玉
new teacher("秦傑", 16).say(); // 秦傑
call 與 apply 的唯一差別在參數形式:第一個參數都是 this(要指向的對象),call 之後逐一列出參數,apply 的第二個參數必須是陣列或 arguments 物件。
它們的本質是改變函式的 this 指向。JS 手冊的說法是「以另一個對象取代當前對象來呼叫方法」;若省略 thisObj,則 Global 物件會被當成 this。
Math.max(5, 8); // 8
Math.max(5, 7, 9, 3, 1, 6); // 9
var arr = [5, 7, 9, 1];
Math.max(arr); // NaN ← 不work
// 手動迴圈版
function getMax(arr) {
var len = arr.length;
for (var i = 0, ret = arr[0]; i < len; i++) {
ret = Math.max(ret, arr[i]);
}
return ret;
}
// apply 版:把陣列「攤開」成參數列表
function getMax2(arr) { return Math.max.apply(null, arr); }
Math.max 只吃分散的參數,不吃陣列。apply 能把陣列攤成參數清單,一行取代整個迴圈。ES6 的展開語法讓這件事更直觀:Math.max(...arr)。
同樣的技巧也用在 push:
var arr1 = [1, 3, 4], arr2 = [3, 4, 5];
// arr1.push(arr2) 會得到 [1,3,4,[3,4,5]],不是我們要的
for (var i = 0; i < arr2.length; i++) { arr1.push(arr2[i]); }
Array.prototype.push.apply(arr1, arr2); // [1,3,4,3,4,5]
arr1.push(...arr2); // ES6 等效寫法
三種方法各有致命傷,實務上標準做法是「原型鏈 + 構造函數借用」混用:用 call 借用父建構子處理實例屬性,再把父原型上的方法複製到子原型上。ES6 的 class 與 extends 正是把這套模式包裝成語法糖:
class Student extends Person {
constructor(name, age, grade) {
super(name, age); // 等同 Person.call(this, name, age)
this.grade = grade;
}
intr() { alert(this.grade); } // 自動掛在 prototype 上,所有實例共用
}
super() 就是構造函數借用,extends 就是設定原型鏈(Student.prototype.__proto__ === Person.prototype)。寫成 class 之後,方法共用與屬性獨立的問題都由語言本身處理掉了。