萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 原型繼承陷阱深度剖析:共享引用型別導致的副作用與最佳實踐

核心問題:原型鏈上的引用型別會被所有實例共享

JavaScript 採用原型繼承。當父類別的 prototype 上掛載引用型別(物件、陣列、函式)時,所有子實例將共享同一個引用,修改其中一個實例的該屬性,會波及所有其他實例與父原型。

陷阱實戰演示

場景 A:基本型別(安全)

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),互不干擾。

場景 B:引用型別(危險)

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. 方法放在 prototypeChild.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 初始化引用型別現代專案首選

推薦工具函式:$class(兼容類別式繼承 + 原型方法共享)

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'] 獨有陣列

ES5 新增 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 上重新賦值新陣列/物件。

總結:避坑三原則

  1. 資料歸實例,行為歸原型:this.x = ... 放建構子,proto.method = ... 放原型。
  2. 引用型別必須在建構子中初始化新實體:this.arr = []; this.obj = {};。
  3. 繼承時呼叫父建構子:Parent.call(this, ...) 或 super(...) 確保父層資料正確初始化。

遵循原則,即可安心享受原型繼承的記憶體效能優勢,免除共享引用的隱形炸彈。

copyright © 萬盛學電腦網 all rights reserved