程式碼復用是所有工程師的目標,否則每寫一個新功能都從零開始,效率無從談起。但復用模式有好有壞,有些看似聰明的寫法其實埋著坑。本文逐一剖析六種繼承實作,多數都屬於「能跑,但不該用」的類型。
最常見的直覺寫法:用父構造函數建立一個物件,把它指派給子類型的原型。
function inherit(C, P) { C.prototype = new P(); }
function Parent(name) { this.name = name || 'Adam'; }
Parent.prototype.say = function () { return this.name; };
function Child(name) {}
inherit(Child, Parent);
var kid = new Child();
console.log(kid.say()); // "Adam"
var kiddo = new Child();
kiddo.name = "Patrick";
console.log(kiddo.say()); // "Patrick"
// 致命缺陷:參數傳不進 Child
var s = new Child('Seth');
console.log(s.say()); // "Adam",而非 "Seth"
問題很直白:子構造函數收不到參數。僅這一點就足以讓它在真實專案中報廢。
用 apply 把父構造函數借過來執行,並把子類的 this 與參數一起傳入。
function Parent(name) { this.name = name || 'Adam'; }
Parent.prototype.say = function () { return this.name; };
function Child(name) { Parent.apply(this, arguments); }
var kid = new Child("Patrick");
console.log(kid.name); // "Patrick",參數成功傳入
// 但原型上的方法沒繼承過來
console.log(typeof kid.say); // "undefined"
參數問題解決了,原型方法卻全丟了。
把前兩種做法硬湊在一起:
function Parent(name) { this.name = name || 'Adam'; }
Parent.prototype.say = function () { return this.name; };
function Child(name) { Parent.apply(this, arguments); }
Child.prototype = new Parent();
var kid = new Child("Patrick");
console.log(kid.name); // "Patrick"
console.log(typeof kid.say); // "function"
console.log(kid.say()); // "Patrick"
delete kid.name;
console.log(kid.say()); // "Adam"
功能確實正常了,但仔細看:Parent 被執行了兩次——一次在 Child.prototype = new Parent(),一次在 Parent.apply 裡。能跑,但浪費。
讓子類與父類共用同一個原型物件:
function inherit(C, P) { C.prototype = P.prototype; }
function Parent(name) { this.name = name || 'Adam'; }
Parent.prototype.say = function () { return this.name; };
function Child(name) {}
inherit(Child, Parent);
var kid = new Child('Patrick');
console.log(kid.name); // undefined,參數依然沒接收到
console.log(typeof kid.say); // "function"
kid.name = 'Patrick';
console.log(kid.say()); // "Patrick"
更麻煩的是,因為共用同一個原型,任何對 Child.prototype 的修改都會污染 Parent.prototype,反之亦然。這是隱性的災難來源。
也就是俗稱的「經典繼承」:先用一個空的臨時函數做中介,再把子類原型指向它的實例,最後修正 constructor 指針。
/* 閉包封裝 */
var inherit = (function () {
var F = function () { };
return function (C, P) {
F.prototype = P.prototype;
C.prototype = new F();
C.uber = P.prototype;
C.prototype.constructor = C;
};
})();
function Parent(name) { this.name = name || 'Adam'; }
Parent.prototype.say = function () { return this.name; };
function Child(name) {}
inherit(Child, Parent);
var kid = new Child();
console.log(kid.name); // undefined
console.log(typeof kid.say); // "function"
kid.name = 'Patrick';
console.log(kid.say()); // "Patrick"
var kid2 = new Child("Tom");
console.log(kid.constructor.name); // "Child"
console.log(kid.constructor === Parent); // false
這個模式避開了重複呼叫父構造函數的浪費,算是相對乾淨的實作。但參數問題依舊存在——要傳參數,還是得搭配模式二的 Parent.apply(this, arguments)。
有人試圖把整套機制包成一個類似其他語言 class 關鍵字的工廠函數:
var klass = function (Parent, props) {
var Child, F, i;
// 1. 新構造函數
Child = function () {
if (Child.uber && Child.uber.hasOwnProperty("__construct")) {
Child.uber.__construct.apply(this, arguments);
}
if (Child.prototype.hasOwnProperty("__construct")) {
Child.prototype.__construct.apply(this, arguments);
}
};
// 2. 繼承
Parent = Parent || Object;
F = function () { };
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.uber = Parent.prototype;
Child.prototype.constructor = Child;
// 3. 掛上實作方法
for (i in props) {
if (props.hasOwnProperty(i)) {
Child.prototype[i] = props[i];
}
}
return Child;
};
var Man = klass(null, {
__construct: function (what) {
console.log("Man's constructor");
this.name = what;
},
getName: function () { return this.name; }
});
var first = new Man('Adam'); // logs "Man's constructor"
first.getName(); // "Adam"
var SuperMan = klass(Man, {
__construct: function (what) {
console.log("SuperMan's constructor");
},
getName: function () {
var name = SuperMan.uber.getName.call(this);
return "I am " + name;
}
});
var clark = new SuperMan('Clark Kent');
clark.getName(); // "I am Clark Kent"
console.log(clark instanceof Man); // true
console.log(clark instanceof SuperMan); // true
功能上確實完整,但語法風格被硬掰成另一門語言的樣子,在 JavaScript 的生態裡顯得格格不入。願不願意為團隊引入這種心智負擔,值得三思。
六種寫法各有取捨,但沒有一個是全面優美的:模式一、四有污染與參數問題,模式二丟方法,模式三浪費效能,模式五需搭配借用構造函數,模式六語法成本過高。理解它們的缺陷比記住它們的写法更重要——真正該問的是:在 ES6 的 class 與 extends 已經成為標準的今天,這些模式還有幾個存在的理由?