繼承是物件導向的核心話題,而 JavaScript 因為沒有 class(ES6 之前),衍生出了多種截然不同的實作思路。本文把常見的繼承模式逐一拆解,並比較各自的優缺點。
最直觀的做法:讓子類型的原型指向父類型的一個實例,屬性與方法便沿著原型鏈一路往上查找。
function Person(){}
Person.prototype = {
constructor: Person,
name: "Oliver"
};
function People(){}
People.prototype = new Person();
People.prototype.constructor = People;
People.prototype.sayName = function(){
return this.name;
};
var ins = new People();
console.log(ins.sayName());
缺點很明顯:原型上的引用型別屬性會被所有實例共享。
做法是在子類型建構函式裡呼叫父類型,讓每個實例都擁有一份自己的屬性副本。
不傳參數:
function SuperType(){
this.color = ["red", "yellow", "white"];
}
function SubType(){
SuperType.call(this);
}
var instance1 = new SubType();
var instance2 = new SubType();
instance1.color.pop();
console.log(instance1.color); // ["red", "yellow"]
console.log(instance2.color); // ["red", "yellow", "white"]
可以看到兩個實例各自持有獨立的陣列,互不干擾。
可以傳參數:
function SuperType(name){
this.name = name;
this.number = [21, 32, 14, 1];
}
function SubType(name, age){
SuperType.call(this, name);
this.age = age;
}
var instance1 = new SubType("Oliver", 18);
var instance2 = new SubType("Troy", 24);
instance2.number.pop();
console.log(instance1.name + instance1.age + instance1.number); // Oliver1821,32,14,1
console.log(instance2.name + instance2.age + instance2.number); // Troy2421,32,14
它的問題是方法只能在建構函式內部定義,無法共用原型上的方法,職責難以分離。
把兩者結合:用借用建構函式處理實例屬性,用原型鏈處理方法共用,是最常使用的方案。
不傳參數:
function SuperType(){
this.color = ["red", "yellow", "white"];
}
SuperType.prototype.sayColor = function(){
return this.color;
};
function SubType(){
SuperType.call(this);
this.number = 321;
}
SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType;
SubType.prototype.sayNumber = function(){
return this.number;
};
var instance1 = new SubType();
var instance2 = new SubType();
instance2.color.pop();
console.log(instance1.color + instance1.number); // red,yellow,white321
console.log(instance2.color + instance2.number); // red,yellow321
可以傳參數:
function SuperType(name){
this.name = name;
this.number = [32, 1342, 11, 1];
}
SuperType.prototype.sayName = function(){
return this.name;
};
function SubType(name, age){
SuperType.call(this, name);
this.age = age;
}
SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType;
SubType.prototype.sayAge = function(){
return this.age;
};
var instance1 = new SubType("Oliver", 18);
var instance2 = new SubType("Troy", 24);
instance2.number.pop();
console.log(instance1.sayName() + instance1.sayAge() + instance1.number); // Oliver1832,1342,11,1
console.log(instance2.sayName() + instance2.sayAge() + instance2.number); // Troy2432,1342,11
組合繼承的']).place