JavaScript 採用原型繼承。當父類別的 prototype 上掛載引用型別(物件、陣列、函式)時,所有子實例將共享同一個引用,修改其中一個實例的該屬性,會波及所有其他實例與父原型。
function create(parent) {
function F() {}
F.prototype = parent;
return new F();
}
const parent = { name: 'Jack', age: 30, married: false };
const child = create(parent);
child.name = 'Lily';
child.age = 20;
child.married = true;
console.log(parent); // { name: 'Jack', age: 30, married: false } ← 未受影響
console.log(child); // { name: 'Lily', age: 20, married: true }
基本型別(字串、數字、布林)賦值時會建立新值,覆蓋原型鏈上的同名屬性(遮蔽 shadowing),互不干擾。
const parent = {
data: { name: 'Jack', age: 30, married: false },
langs: ['Java']
};
const child = create(parent);
child.data.name = 'Lily';
child.data.age = 20;
child.data.married = true;
child.langs.push('JavaScript');
console.log(parent.data); // { name: 'Lily', age: 20, married: true } ← 被修改!
console.log(parent.langs); // ['Java', 'JavaScript'] ← 被修改!
child.data 與 parent.data 指向同一個物件;push 修改陣列內容,同樣影響共享引用。
| 策略 | 做法 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|---|
1. 資料屬性掛在實例(this) | 建構子內 this.data = { ... } | 每實例獨擁、可透過參數初始化 | 每實例佔記憶體、方法無法共享 | 狀態資料、巢狀物件、陣列 |
| 2. 方法放在 prototype | Child.prototype.method = fn | 記憶體共享、子類可安全覆寫 | 無法存取實例私有變數(需靠 this) | 行為邏輯、工具函式 |
| 3. Object.create + 初始化函式 | const child = Object.create(parent); child.init(...) | 標準 API、語意清晰 | 需手動初始化、易忘 | 簡單繼承、無建構子需求 |
| 4. 深層克隆(序列化/遞迴複製) | JSON.parse(JSON.stringify(parent)) 或 lodash.cloneDeep | 徹底斷開引用 | 效能較差、無法處理函式/循環引用 | 配置物件、快照備份 |
| 5. ES6 Class + super() | class Child extends Parent { constructor(){ super(); this.data = {...} } } | 語法標準、工具鏈支援完善 | 仍需注意在 constructor 初始化引用型別 | 現代專案首選 |
function $class(className, superClass, factory) {
if (superClass === '') superClass = Object;
function Clazz() {
if (typeof this.init === 'function') {
this.init.apply(this, arguments);
}
}
Clazz.prototype = new superClass(); // 原型鏈
Clazz.prototype.constructor = Clazz;
Clazz.prototype.className = className;
window[className] = Clazz; // 全域註冊(可選)
factory.call(Clazz.prototype, superClass.prototype); // factory 接收 superPrototype
}
// 使用範例
$class('Animal', Object, function (superProto) {
this.init = function (name) { this.name = name; this.sounds = []; };
this.speak = function () { console.log(this.name + ' says ' + this.sounds.join(', ')); };
});
$class('Dog', Animal, function (superProto) {
this.init = function (name, breed) {
superProto.init.call(this, name); // 呼叫父初始化
this.breed = breed;
this.sounds.push('Woof');
};
});
const d = new Dog('Lucky', 'Beagle');
d.speak(); // "Lucky says Woof"
console.log(d.sounds); // ['Woof'] 獨有陣列
Object.create 簡化原型繼承const parent = { name: 'Jack', age: 30 };
const child = Object.create(parent);
child.name = 'Lily'; // 遮蔽
console.log(parent.name); // 'Jack' 安全
但同樣需注意:child.arr.push(1) 仍會修改共享陣列,建議在 child 上重新賦值新陣列/物件。
this.x = ... 放建構子,proto.method = ... 放原型。this.arr = []; this.obj = {};。Parent.call(this, ...) 或 super(...) 確保父層資料正確初始化。遵循原則,即可安心享受原型繼承的記憶體效能優勢,免除共享引用的隱形炸彈。