繼承是個老話題,但很多人講不清楚。JavaScript 對繼承的原生支援確實不理想,需要工程師自己搭一套機制。下面由淺入深地梳理一遍。
1. 直接用原型鏈
最直覺也最粗糙的一種,幾乎無法用於真實專案。
function SuperType(){ this.property = true; }
SuperType.prototype.getSuperValue = function(){ return this.property; }
function SubType(){ this.subproperty = false; }
SubType.prototype = new SuperType(); // 繼承
SubType.prototype.getSubValue = function(){ return this.subproperty; }
var instance = new SubType();
問題在於原型上的屬性會被所有實例共享,透過一個實例改動繼承而來的屬性,會連帶影響其他實例。這顯然不是常識意義上的繼承。
2. 使用構造函數
構造函數本質上就是函數,可以在任何作用域呼叫;在子類構造函數裡呼叫父類,就完成了簡單繼承。
function SuperType(){ this.colors = ["red", "blue", "green"]; }
function SubType(){ SuperType.call(this); }
var instance = new SubType();
這解決了共享問題,但換來新的麻煩:函數無法共享,而且 instance instanceof SuperType 為 false。
3. 原型與構造函數組合
function SuperType(name){
this.name = name;
this.colors = ["red", "blue", "green"];
}
SuperType.prototype.sayName = function(){ /* code */ };
function SubType(name, age){
SuperType.call(this, name); // 第二次呼叫
this.age = age;
}
SubType.prototype = new SuperType(); // 第一次呼叫
var instance = new SubType();
這是最常用的繼承模式:每個實例有自己的屬性,同時能共享原型上的方法。缺點是父類構造函數一定會被呼叫兩次——一次在建置子類原型時,一次在子類構造函數內部。
4. 寄生組合式繼承
子類原型並不必是父類的實例,只要是一個「原型指向父類原型」的普通物件即可。Douglas Crockford 的寫法:
function object(o){
function F(){};
F.prototype = o;
return new F();
}
這正是 ES5 中 Object.create 的實作。於是第 3 種方案可以改成:
function inheritPrototype(subType, superType){
var prototype = object(superType.prototype);
prototype.constructor = subType;
subType.prototype = prototype;
}
function SuperType(name){
this.name = name;
this.colors = ["red", "blue", "green"];
}
SuperType.prototype.sayName = function(){ /* code */ };
function SubType(name, age){
SuperType.call(this, name); // 只呼叫一次
this.age = age;
}
inheritPrototype(SubType, SuperType);
var instance = new SubType();
寄生組合式已經足以應付日常需求。但如果要求再高一點——如何在子類中呼叫父類的同名方法呢?
5. simple-inheritance 的實作
初次看到這段程式碼大概會卻步,但讀懂之後會發現設計相當精妙。以下逐行加上註解。
(function(){
// initializing 用於控制類的初始化,是整段程式碼最巧妙的地方
// fnTest 偵測函數中是否出現 _super,只在需要時才包裝,藉此提升效能
var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
// 所有類的基類
this.Class = function(){};
// 為基類加上 extend,用於繼承
Class.extend = function(prop){
var _super = this.prototype;
// 以父類實例作為子類原型,並透過 initializing 避免觸發父類初始化
initializing = true;
var prototype = new this();
initializing = false;
// 把 prop 上的成員複製到 prototype
for (var name in prop) {
// 只有子類方法用到 _super 時才做包裝
prototype[name] = typeof prop[name] == "function" &&
typeof _super[name] == "function" && fnTest.test(prop[name]) ?
(function(name, fn){
return function(){
var tmp = this._super;
this._super = _super[name]; // 暫時指向父類同名方法
fn.apply(this, arguments);
if (tmp) { this._super = tmp; } // 還原
};
})(name, prop[name]) : prop[name];
}
// new 一個物件時,實際上是呼叫原型上的 init
function Class(){
if (!initializing && this.init) {
this.init.apply(this, arguments);
}
}
Class.prototype = prototype;
Class.prototype.constructor = Class;
Class.extend = arguments.callee;
return Class;
};
})();
最精妙的一點是「按需重寫」:只有當子類方法裡真的出現 _super 時才做包裝,並在實例中透過 this._super 呼叫父類同名方法,寫起來非常接近 Java 那類靜態語言。
使用起來就相當直觀了:
var Human = Class.extend({
init: function(age, name){
this.age = age;
this.name = name;
},
say: function(){ console.log("I am a human"); }
});
var Man = Human.extend({
init: function(age, name, height){
this._super(age, name);
this.height = height;
},
say: function(){
this._super();
console.log("I am a man");
}
});
var man = new Man(21, 'bob', '191');
man.say();