Mixin 是 JavaScript 裡很實用的一招:把某個物件的方法「摻」進另一個類別,不必建立繼承關係。下面這個 augment 就是最小可用的實作,並附一個改進版。
<script type="text/javascript">
/* 增加函數:基本版 */
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];
}
}
}
}
var Author = function Author(name, books) {
this.name = name;
this.books = books || 'default value';
};
Author.prototype = {
getName: function () { return this.name; },
getBooks: function () { return this.books; }
};
var Editor = function Editor() {};
Editor.prototype = {
hello: function () { return 'Hello,' + this.name; }
};
augment(Author, Editor); // 把 hello 摻進 Author
var author = new Author('Ross Harmes', ['JavaScript Design Patterns']);
console.log(author.getName()); // Ross Harmes
console.log(author.getBooks()); // ['JavaScript Design Patterns']
console.log(author.hello()); // Hello,Ross Harmes
</script>
結果:

經過 mix 之後,author 獲得了 hello 方法,而 name 屬性仍是自己的。
if (!receivingClass.prototype[methodName]) 是保護,不是多餘。它保證「已經存在的方法不會被蓋掉」。少了這行,只要 mixin 剛好有一個同名方法,原本的實作就會被靜默替換,而且很難查。副作用是:若你「想」覆寫某個方法,augment 反而幫不上忙,得直接指派。
用 for...in 時要留意可枚舉屬性。如果 givingClass.prototype 是直接用物件字面值設定的,沒問題;但若有人幫它擴充了 enumerable 的自訂屬性,那些也會被一起拷過來。嚴謹一點的寫法會加上 hasOwnProperty 檢查。
改進版用 arguments[2] 判斷有沒有傳入指定方法。這個設計讓同一個函式同時支援「全給」與「挑著給」兩種用法,呼叫方式分別是 augment(A, B) 與 augment(A, B, 'method1', 'method2')。缺點是參數意義不明顯,可讀性不如另外開一個函式。
ES6 之後,同樣的效果一行就夠了:
Object.assign(Author.prototype, Editor.prototype);
// 或只挑指定方法
Object.assign(Author.prototype, {
hello: Editor.prototype.hello
});
差別在於 Object.assign 會無條件覆寫(相當於拿掉 if 判斷的版本),而且只複製「自有且可枚舉」的屬性,行為更明確可預測。若真的需要 mixin 的「不覆蓋」語意,自己寫的那個 augment 仍有存在價值。
以上就是這篇的全部內容,希望對你的 JavaScript 開發有幫助。