JavaScript 沒有 class 關鍵字(ES6 之前),要達到類似的效果得靠三種手法:類擴展(extend)、對象克隆(clone)與混合類(augment)。本文用同一個「就地編輯」的元件示範三者。
核心是一個 extend 函式:建立一個空的暫存建構函式,把父類的 prototype 掛上去,再讓子類繼承這個暫存物件,最後把 constructor 指回自己。
/* EditInPlaceField 類 */
/* 擴展函數 */
function extend(subClass, superClass) {
var F = function () {};
F.prototype = superClass.prototype;
subClass.prototype = new F();
subClass.prototype.constructor = subClass;
subClass.superclass = superClass.prototype;
if (superClass.prototype.constructor == Object.prototype.constructor) {
superClass.prototype.constructor = superClass;
}
}
function EditInPlaceField(id, parent, value) {
this.id = id;
this.value = value || 'default value';
this.parentElement = parent;
this.createElements(this.id);
this.attachEvents();
}
EditInPlaceField.prototype = {
createElements: function (id) {
this.containerElement = document.createElement('div');
this.parentElement.appendChild(this.containerElement);
this.staticElement = document.createElement('span');
this.containerElement.appendChild(this.staticElement);
this.staticElement.innerHTML = this.value;
this.fieldElement = document.createElement('input');
this.fieldElement.type = 'text';
this.fieldElement.value = this.value;
this.containerElement.appendChild(this.fieldElement);
this.saveButton = document.createElement('input');
this.saveButton.type = 'button';
this.saveButton.value = 'Save';
this.containerElement.appendChild(this.saveButton);
this.cancelButton = document.createElement('input');
this.cancelButton.type = 'button';
this.cancelButton.value = 'Cancel';
this.containerElement.appendChild(this.cancelButton);
this.convertToText();
},
attachEvents: function () {
var that = this;
addEvent(this.staticElement, 'click', function () { that.convertToEditable(); });
addEvent(this.saveButton, 'click', function () { that.save(); });
addEvent(this.cancelButton, 'click', function () { that.cancel(); });
},
convertToEditable: function () {
this.staticElement.style.display = 'none';
this.fieldElement.style.display = 'inline';
this.saveButton.style.display = 'inline';
this.cancelButton.style.display = 'inline';
this.setValue(this.value);
},
save: function () {
this.value = this.getValue();
var that = this;
var callback = {
success: function () { that.convertToText(); },
failure: function () { alert('Error saving value.'); }
};
ajaxRequest('GET', 'save.php?id=' + this.id + '&value=' + this.value, callback);
},
cancel: function () { this.convertToText(); },
convertToText: function () {
this.fieldElement.style.display = 'none';
this.saveButton.style.display = 'none';
this.cancelButton.style.display = 'none';
this.staticElement.style.display = 'inline';
this.setValue(this.value);
},
setValue: function (value) {
this.fieldElement.value = value;
this.staticElement.innerHTML = value;
},
getValue: function () { return this.fieldElement.value; }
};
var titleClassical = new EditInPlaceField('titleClassical', $('doc'), 'Title Here');
var currentTitleText = titleClassical.getValue();
/* EditInPlaceArea 類:繼承並覆寫部分方法 */
function EditInPlaceArea(id, parent, value) {
EditInPlaceArea.superclass.constructor.call(this, id, parent, value);
}
extend(EditInPlaceArea, EditInPlaceField);
// 覆寫:改用 textarea 與 p
EditInPlaceArea.prototype.createElements = function (id) {
this.containerElement = document.createElement('div');
this.parentElement.appendChild(this.containerElement);
this.staticElement = document.createElement('p');
this.containerElement.appendChild(this.staticElement);
this.staticElement.innerHTML = this.value;
this.fieldElement = document.createElement('textarea');
this.fieldElement.value = this.value;
this.containerElement.appendChild(this.fieldElement);
this.saveButton = document.createElement('input');
this.saveButton.type = 'button';
this.saveButton.value = 'Save';
this.containerElement.appendChild(this.saveButton);
this.cancelButton = document.createElement('input');
this.cancelButton.type = 'button';
this.cancelButton.value = 'Cancel';
this.containerElement.appendChild(this.cancelButton);
this.convertToText();
};
EditInPlaceArea.prototype.convertToEditable = function () {
this.staticElement.style.display = 'none';
this.fieldElement.style.display = 'block';
this.saveButton.style.display = 'inline';
this.cancelButton.style.display = 'inline';
this.setValue(this.value);
};
EditInPlaceArea.prototype.convertToText = function () {
this.fieldElement.style.display = 'none';
this.saveButton.style.display = 'none';
this.cancelButton.style.display = 'none';
this.staticElement.style.display = 'block';
this.setValue(this.value);
};
那個 var F = function () {} 的中間層是關鍵。若直接寫 subClass.prototype = superClass.prototype,子類改 prototype 會連父類一起改掉;透過空建構函式繞一圈,子類拿到的是原型鏈上的一個新環節,父子互不干擾。
克隆的思路更輕:不建立類,直接複製一個現成物件作為原型。
/* 克隆函數 */
function clone(object) {
function F() {}
F.prototype = object;
return new F;
}
var EditInPlaceField = {
configure: function (id, parent, value) {
this.id = id;
this.value = value || 'default value';
this.parentElement = parent;
this.createElements(this.id);
this.attachEvents();
},
createElements: function (id) {
this.containerElement = document.createElement('div');
this.parentElement.appendChild(this.containerElement);
this.staticElement = document.createElement('span');
this.containerElement.appendChild(this.staticElement);
this.staticElement.innerHTML = this.value;
this.fieldElement = document.createElement('input');
this.fieldElement.type = 'text';
this.fieldElement.value = this.value;
this.containerElement.appendChild(this.fieldElement);
this.saveButton = document.createElement('input');
this.saveButton.type = 'button';
this.saveButton.value = 'Save';
this.containerElement.appendChild(this.saveButton);
this.cancelButton = document.createElement('input');
this.cancelButton.type = 'button';
this.cancelButton.value = 'Cancel';
this.containerElement.appendChild(this.cancelButton);
this.convertToText();
},
attachEvents: function () {
var that = this;
addEvent(this.staticElement, 'click', function () { that.convertToEditable(); });
addEvent(this.saveButton, 'click', function () { that.save(); });
addEvent(this.cancelButton, 'click', function () { that.cancel(); });
},
convertToEditable: function () {
this.staticElement.style.display = 'none';
this.fieldElement.style.display = 'inline';
this.saveButton.style.display = 'inline';
this.cancelButton.style.display = 'inline';
this.setValue(this.value);
},
save: function () {
this.value = this.getValue();
var that = this;
var callback = {
success: function () { that.convertToText(); },
failure: function () { alert('Error saving value.'); }
};
ajaxRequest('GET', 'save.php?id=' + this.id + '&value=' + this.value, callback);
},
cancel: function () { this.convertToText(); },
convertToText: function () {
this.fieldElement.style.display = 'none';
this.saveButton.style.display = 'none';
this.cancelButton.style.display = 'none';
this.staticElement.style.display = 'inline';
this.setValue(this.value);
},
setValue: function (value) {
this.fieldElement.value = value;
this.staticElement.innerHTML = value;
},
getValue: function () { return this.fieldElement.value; }
};
var titlePrototypal = clone(EditInPlaceField);
titlePrototypal.configure('titlePrototypal', $('doc'), 'Title Here');
var currentTitleText = titlePrototypal.getValue();
/* EditInPlaceArea:克隆後覆寫部分方法 */
var EditInPlaceArea = clone(EditInPlaceField);
EditInPlaceArea.createElements = function (id) {
this.containerElement = document.createElement('div');
this.parentElement.appendChild(this.containerElement);
this.staticElement = document.createElement('p');
this.containerElement.appendChild(this.staticElement);
this.staticElement.innerHTML = this.value;
this.fieldElement = document.createElement('textarea');
this.fieldElement.value = this.value;
this.containerElement.appendChild(this.fieldElement);
this.saveButton = document.createElement('input');
this.saveButton.type = 'button';
this.saveButton.value = 'Save';
this.containerElement.appendChild(this.saveButton);
this.cancelButton = document.createElement('input');
this.cancelButton.type = 'button';
this.cancelButton.value = 'Cancel';
this.containerElement.appendChild(this.cancelButton);
this.convertToText();
};
EditInPlaceArea.convertToEditable = function () {
this.staticElement.style.display = 'none';
this.fieldElement.style.display = 'block';
this.saveButton.style.display = 'inline';
this.cancelButton.style.display = 'inline';
this.setValue(this.value);
};
EditInPlaceArea.convertToText = function () {
this.fieldElement.style.display = 'none';
this.saveButton.style.display = 'none';
this.cancelButton.style.display = 'none';
this.staticElement.style.display = 'block';
this.setValue(this.value);
};
注意克隆版的初始化方法叫 configure 而不是建構函式——因為它本質上不是類,只是一個被當成原型的普通物件。這也解釋了為什麼覆寫時是直接 EditInPlaceArea.createElements = function...,前面沒有 .prototype。
前兩種都是「A 繼承 B」,混合類解決的是另一個問題:把散在多個地方的實作「摻」進來,不必建立繼承關係。
/* 基本版混合函數 */
function augment(receivingClass, givingClass) {
for (var methodName in givingClass.prototype) {
if (!receivingClass.prototype[methodName]) {
receivingClass.prototype[methodName] = givingClass.prototype[methodName];
}
}
}
/* 改進版:可以只挑指定方法 */
function augment(receivingClass, givingClass) {
if (arguments[2]) {
// 只給指定的方法
for (var i = 2, len = arguments.length; i < len; i++) {
receivingClass.prototype[arguments[i]] = givingClass.prototype[arguments[i]];
}
} else {
// 給全部方法
for (var methodName in givingClass.prototype) {
if (!receivingClass.prototype[methodName]) {
receivingClass.prototype[methodName] = givingClass.prototype[methodName];
}
}
}
}
/* 準備一個「mixin 類」,只當容器用 */
var EditInPlaceMixin = function () {};
EditInPlaceMixin.prototype = {
createElements: function (id) {
this.containerElement = document.createElement('div');
this.parentElement.appendChild(this.containerElement);
this.staticElement = document.createElement('span');
this.containerElement.appendChild(this.staticElement);
this.staticElement.innerHTML = this.value;
this.fieldElement = document.createElement('input');
this.fieldElement.type = 'text';
this.fieldElement.value = this.value;
this.containerElement.appendChild(this.fieldElement);
this.saveButton = document.createElement('input');
this.saveButton.type = 'button';
this.saveButton.value = 'Save';
this.containerElement.appendChild(this.saveButton);
this.cancelButton = document.createElement('input');
this.cancelButton.type = 'button';
this.cancelButton.value = 'Cancel';
this.containerElement.appendChild(this.cancelButton);
this.convertToText();
},
attachEvents: function () {
var that = this;
addEvent(this.staticElement, 'click', function () { that.convertToEditable(); });
addEvent(this.saveButton, 'click', function () { that.save(); });
addEvent(this.cancelButton, 'click', function () { that.cancel(); });
},
convertToEditable: function () {
this.staticElement.style.display = 'none';
this.fieldElement.style.display = 'inline';
this.saveButton.style.display = 'inline';
this.cancelButton.style.display = 'inline';
this.setValue(this.value);
},
save: function () {
this.value = this.getValue();
var that = this;
var callback = {
success: function () { that.convertToText(); },
failure: function () { alert('Error saving value.'); }
};
ajaxRequest('GET', 'save.php?id=' + this.id + '&value=' + this.value, callback);
},
cancel: function () { this.convertToText(); },
convertToText: function () {
this.fieldElement.style.display = 'none';
this.saveButton.style.display = 'none';
this.cancelButton.style.display = 'none';
this.staticElement.style.display = 'inline';
this.setValue(this.value);
},
setValue: function (value) {
this.fieldElement.value = value;
this.staticElement.innerHTML = value;
},
getValue: function () { return this.fieldElement.value; }
};
/* EditInPlaceField 類 */
function EditInPlaceField(id, parent, value) {
this.id = id;
this.value = value || 'default value';
this.parentElement = parent;
this.createElements(this.id);
this.attachEvents();
}
augment(EditInPlaceField, EditInPlaceMixin);
/* EditInPlaceArea 類 */
function EditInPlaceArea(id, parent, value) {
this.id = id;
this.value = value || 'default value';
this.parentElement = parent;
this.createElements(this.id);
this.attachEvents();
}
// 先定義自己的版本,augment 就不會覆蓋它
EditInPlaceArea.prototype.createElements = function (id) {
this.containerElement = document.createElement('div');
this.parentElement.appendChild(this.containerElement);
this.staticElement = document.createElement('p');
this.containerElement.appendChild(this.staticElement);
this.staticElement.innerHTML = this.value;
this.fieldElement = document.createElement('textarea');
this.fieldElement.value = this.value;
this.containerElement.appendChild(this.fieldElement);
this.saveButton = document.createElement('input');
this.saveButton.type = 'button';
this.saveButton.value = 'Save';
this.containerElement.appendChild(this.saveButton);
this.cancelButton = document.createElement('input');
this.cancelButton.type = 'button';
this.cancelButton.value = 'Cancel';
this.containerElement.appendChild(this.cancelButton);
this.convertToText();
};
EditInPlaceArea.prototype.convertToEditable = function () {
this.staticElement.style.display = 'none';
this.fieldElement.style.display = 'block';
this.saveButton.style.display = 'inline';
this.cancelButton.style.display = 'inline';
this.setValue(this.value);
};
EditInPlaceArea.prototype.convertToText = function () {
this.fieldElement.style.display = 'none';
this.saveButton.style.display = 'none';
this.cancelButton.style.display = 'none';
this.staticElement.style.display = 'block';
this.setValue(this.value);
};
augment(EditInPlaceArea, EditInPlaceMixin);
if (!receivingClass.prototype[methodName]) 這個判斷是混合的靈魂:只補上對方還沒有的方法,已經存在的保留不動。所以 EditInPlaceArea 必須「先」定義自己的 createElements,「再」呼叫 augment,順序顛倒就會被 mixin 的版本蓋掉。
JavaScript 的物件系統包含類、對象、函數,往下又分屬性、方法、私有函數、公有函數、靜態函數等。這三個小函式看似只是語法練習,實際代表的正是三種不同的複用策略:
類擴展(extend)建立的是「is-a」的繼承關係,適合子類要沿用父類大部分行為、只改少數部分的情況。
對象克隆(clone)省掉建構函式的繁文縟節,適合以「一個現成的範本物件」為中心展開的設計,改動時只需覆寫屬性。
混合類(augment)表達的是「能不能做這些事」的能力彙集,當一個類需要同時具備來自多個來源的能力、又不方便建立多重繼承時,這是最合適的工具。
ES6 的 class/extends 只是上述機制的語法糖,而 mixin 在現代寫法裡通常以 Object.assign(SubClass.prototype, Mixin) 或 ES2015 的 mixin 函式形式出現。理解底層這三招,讀框架原始碼時會順暢很多。
以上就是這篇的全部內容,希望對你的 JavaScript 開發有幫助。