我最早掌握的繼承寫法來自 w3school 的「混合原型鏈 + 對象冒充」,簡單、思路清晰,一直滿足需求,所以從沒想過要換寫法。直到讀了三生石上關於 JavaScript 繼承的系列文章,才發現繼承機制也可以寫得貼近 Java 那種後端語言的風格。本文在理解其思路的基礎上,逐步構造一個自己往後真正用得上的繼承庫。
// 父類建構函數
function Employee(name, salary) {
this.name = name; // 實例屬性
this.salary = salary; // 實例屬性
}
// 用字面量設定原型,添加實例方法
Employee.prototype = {
constructor: Employee, // 必須修正 constructor 指向
getName: function () { return this.name; },
getSalary: function () { return this.salary; },
toString: function () {
return this.name + '\'s salary is ' + this.getSalary() + '.';
}
};
// 子類建構函數
function Manager(name, salary, percentage) {
Employee.apply(this, [name, salary]); // 對象冒充,繼承屬性
this.percentage = percentage;
}
Manager.prototype = new Employee(); // 原型鏈繼承方法
Manager.prototype.constructor = Manager;
Manager.prototype.getSalary = function () {
return this.salary + this.salary * this.percentage;
};
var e = new Employee('jason', 5000);
var m = new Manager('tom', 8000, 0.15);
console.log(e.toString()); // jason's salary is 5000.
console.log(m.toString()); // tom's salary is 9200.
從結果看沒問題,但從代碼組織與實現細節來看,有五個值得改進的地方。
每個子類都要重複這套結構:
SubClass.prototype = new SuperClass();
SubClass.prototype.constructor = SubClass;
SubClass.prototype.method1 = function () {}
SubClass.prototype.method2 = function () {}
而且添加實例方法時不能寫成 SubClass.prototype = { method1: ... },否則會整個覆蓋掉原型,繼承就斷了。這種束縛讓代碼看起來很不連貫。
解法:把通用邏輯封裝成模塊,對外只暴露簡單介面。
JavaScript 函數無法重載,父類不可能提供多個建構函數。實務上父類建構函數通常有參數,只能靠 arguments.length 模擬重載,而這很容易忘記寫。
解法:把建構函數全部無參化,邏輯遷移到 init 方法:
function Employee() {}
Employee.prototype = {
constructor: Employee,
init: function (name, salary) {
this.name = name;
this.salary = salary;
},
getName: function () { return this.name; },
getSalary: function () { return this.salary; },
toString: function () {
return this.name + '\'s salary is ' + this.getSalary() + '.';
}
};
function Manager() {}
Manager.prototype = new Employee();
Manager.prototype.constructor = Manager;
Manager.prototype.init = function (name, salary, percentage) {
Employee.prototype.init.apply(this, [name, salary]); // 借用父類 init
this.percentage = percentage;
};
代價是使用時要手動多呼叫一次 init:
var e = new Employee();
e.init('jason', 5000);
能否把 init 放進建構函數?可以,只要加一個全局標識避免在「建立原型」階段被誤觸:
var initializing = false;
function Employee() {
if (!initializing) {
this.init.apply(this, arguments);
}
}
// ... 原型定義 ...
initializing = true;
Manager.prototype = new Employee(); // 此時不觸發 init
Manager.prototype.constructor = Manager;
initializing = false;
剩下的問題是:這個 initializing 全局變數能不能藏起來?把整件事封裝進模塊即可。
SubClass.prototype = new SuperClass() 是類與實例之間的關係,而繼承本該發生在類與類之間。它還會增加原型鏈長度,層數深了會拖慢方法查找。
解法:既然約定「實例屬性寫在建構函數、實例方法寫在原型」,那麼原型上就只會有方法,直接複製即可,不必繞一圈透過實例:
var copy = function (source) {
var target = {};
for (var i in source) {
if (source.hasOwnProperty(i)) {
target[i] = source[i];
}
}
return target;
};
function Manager() {
this.init.apply(this, arguments);
}
Manager.prototype = copy(Employee.prototype);
Manager.prototype.constructor = Manager; // 仍需修正指向
var m = new Manager('tom', 8000, 0.15);
console.log(m.toString()); // tom's salary is 9200.
console.log(m instanceof Employee); // false
這樣 m.toString() 呼叫的是 Manager 自身原型上的方法,查找距離大幅縮短。代價是原型鏈斷了,m instanceof Employee 變成 false。但 instanceof 在實務中幾乎用不到,而方法確實繼承下來了——這才是繼承的主要目的。
額外好處:既然不再呼叫父類建構函數,initializing 那個全局變數也就不需要了。
每次都得分別寫 SuperClass.apply(this) 和 SuperClass.prototype.method1.apply(this, arguments)。理想寫法是:
function SubClass() {
this.base(); // 調用父類建構
}
SubClass.prototype.method1 = function () {
this.base(); // 調用父類同名方法
}
解法:用方法代理。因為 this.base 需要動態指向「父類原型上的同名方法」,所以要在每個實例方法執行期間臨時改寫它,執行完再還原:
Manager.prototype.init = (function (name, func) {
return function () {
var old = this.base; // 記錄原本的值
this.base = this.baseProto[name]; // 指向父類同名方法
var ret = func.apply(this, arguments); // 執行子類自己的方法
this.base = old; // 還原
return ret;
};
})('init', function (name, salary, percentage) {
this.base(name, salary); // 透過 this.base 調用父類 init
this.percentage = percentage;
});
前提是每個實例都要有 baseProto 屬性能指到父類原型(因為 copy 導致原型鏈斷裂):
function Manager() {
this.baseProto = Employee.prototype;
this.init.apply(this, arguments);
}
JavaScript 沒有原生的靜態成員語法,實務上掛在建構函數上是最合適的位置:
Employee.idCounter = 1; // 靜態屬性
Employee.getId = function () { // 靜態方法
return Employee.idCounter++;
};
靜態方法內部用 this 就能訪問其他靜態成員,因為呼叫 Employee.getId() 時 this 指向 Employee 本身。
先定目標,再反推實現——這比一頭栽進代碼有效得多。我希望的使用方式如下:
var Employee = Class({
instanceMembers: {
init: function (name, salary) {
this.name = name;
this.salary = salary;
this.id = Employee.getId(); // 調用靜態方法
},
getName: function () { return this.name; },
getSalary: function () { return this.salary; },
toString: function () {
return this.name + '\'s salary is ' + this.getSalary() + '.';
}
},
staticMembers: {
idCounter: 1,
getId: function () { return this.idCounter++; }
}
});
var Manager = Class({
instanceMembers: {
init: function (name, salary, percentage) {
this.base(name, salary); // 簡潔的父類調用
this.percentage = percentage;
},
getSalary: function () {
return this.base() + this.salary * this.percentage;
}
},
extend: Employee
});
對外只需要 Class、instanceMembers、staticMembers、extend 四個名稱。
var Class = (function () {
var hasOwn = Object.prototype.hasOwnProperty;
function isObject(o) { return typeof (o) === 'object'; }
function isFunction(f) { return typeof (f) === 'function'; }
function ClassBuilder(options) {
if (!isObject(options)) {
throw new Error('Class options must be an valid object instance!');
}
var instanceMembers = (isObject(options) && options.instanceMembers) || {},
staticMembers = (isObject(options) && options.staticMembers) || {},
extend = (isObject(options) && isFunction(options.extend)) && options.extend,
prop;
// 目標類的建構函數
function TargetClass() {
if (isFunction(this.init)) {
this.init.apply(this, arguments);
}
}
// 靜態成員必須在設定原型之前添加,否則有被覆蓋的風險
for (prop in staticMembers) {
if (hasOwn.call(staticMembers, prop)) {
TargetClass[prop] = staticMembers[prop];
}
}
TargetClass.prototype = instanceMembers;
TargetClass.prototype.constructor = TargetClass;
return TargetClass;
}
return ClassBuilder;
})();
驗證:
var e = new Employee('jason', 5000);
console.log(e.toString()); // jason's salary is 5000.
console.log(e.id); // 1
console.log(e.constructor === Employee); // true
在第一版基礎上加入 copy 函數與 extend 處理:
function copy(source) {
var target = {};
for (var i in source) {
if (hasOwn.call(source, i)) {
target[i] = source[i];
}
}
return target;
}
function TargetClass() {
if (extend) {
// copy 導致原型鏈斷裂,因此給每個實例一個屬性指回父類原型
this.baseProto = extend.prototype;
}
if (isFunction(this.init)) {
this.init.apply(this, arguments);
}
}
// 靜態成員(同上)
// 有父類時,先把父類的實例方法複製過來
extend && (TargetClass.prototype = copy(extend.prototype));
// 再添加自己的實例方法
for (prop in instanceMembers) {
if (hasOwn.call(instanceMembers, prop)) {
TargetClass.prototype[prop] = instanceMembers[prop];
}
}
TargetClass.prototype.constructor = TargetClass;
只需修改添加實例方法的那段迴圈:
for (prop in instanceMembers) {
if (hasOwn.call(instanceMembers, prop)) {
// 只有「需要繼承」且「父類原型存在同名方法」時才代理
if (extend && isFunction(instanceMembers[prop]) && isFunction(extend.prototype[prop])) {
TargetClass.prototype[prop] = (function (name, func) {
return function () {
var old = this.base;
this.base = extend.prototype[name];
var ret = func.apply(this, arguments);
this.base = old;
return ret;
};
})(prop, instanceMembers[prop]);
} else {
TargetClass.prototype[prop] = instanceMembers[prop];
}
}
}
var Employee = Class({
instanceMembers: {
init: function (name, salary) {
this.name = name;
this.salary = salary;
this.id = Employee.getId();
},
getName: function () { return this.name; },
getSalary: function () { return this.salary; },
toString: function () {
return this.name + '\'s salary is ' + this.getSalary() + '.';
}
},
staticMembers: {
idCounter: 1,
getId: function () { return this.idCounter++; }
}
});
var Manager = Class({
instanceMembers: {
init: function (name, salary, percentage) {
this.base(name, salary); // 調用父類 init
this.percentage = percentage;
},
getSalary: function () {
return this.base() + this.salary * this.percentage;
}
},
extend: Employee
});
var e = new Employee('jason', 5000);
var m = new Manager('tom', 8000, 0.15);
console.log(e.toString()); // jason's salary is 5000.
console.log(m.toString()); // tom's salary is 9200.
console.log(e.id); // 1
console.log(m.id); // 2
這個繼承庫做的事,就是把第一部分列出的問題與解法,加上第二部分模擬的調用場景,封裝進一個模塊裡。核心只有三件事:用 init 承擔建構邏輯、用 copy 複製父類原型方法、用代理支援 this.base。
寫組件的時候不能把邏輯寫死,多留介面,等具體專案再透過繼承擴展個性化功能——這樣的組件才夠靈活穩定。這也是我在這個練習中最大的收穫。
補充:ES6 的 class 語法與 extends / super 已把這一切標準化,新專案直接用原生語法即可。本文的價值在於理解背後的原理——原生 class 也不過是原型鏈加上語法糖。