萬盛學電腦網

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

JavaScript 原型鏈繼承完整解析:從原型指向到查找機制

原型鏈是 JavaScript 繼承的核心機制。本文透過貓與老虎的經典範例,詳細解析 prototype 指向、__proto__ 內部連結、屬性查找順序與建構函式關係,並對比 ES6 class extends 底層實現。

核心範例程式碼

<script>
// 父類別:貓物件(字面值建立)
var kitty = {
    color: 'yellow',
    bark: function() { alert('喵喵'); },
    climb: function() { alert('我會爬樹'); }
};

// 子類別建構函式:老虎
function Tiger() {
    this.color = "yellow and black";
    this.bark = function() { alert('吼吼...'); }
}

// 關鍵:將子類別 prototype 指向父物件
Tiger.prototype = kitty;
// 或:Tiger.prototype = new Kitty(); // 若 Kitty 為建構函式

// 建立實例
var t = new Tiger();
document.write(t.color);      // "yellow and black" (實例自有屬性)
t.climb();                    // "我會爬樹" (從原型鏈查找)
</script>

記憶體結構圖解

t (Tiger 實例)
  ├─ color: "yellow and black"      ← 實例自有屬性
  ├─ bark: function() { ... }       ← 實例自有方法
  └─ __proto__ ──────────────────► Tiger.prototype (kitty)
                                      ├─ color: "yellow"
                                      ├─ bark: function() { alert('喵喵') }
                                      ├─ climb: function() { alert('我會爬樹') }
                                      └─ __proto__ ────────► Object.prototype
                                                                      ├─ toString()
                                                                      └─ ...

屬性查找機制:原型鏈遍歷

存取 t.climb() 時:

  1. 檢查 t 自有屬性 → 無
  2. 沿 __proto__ 找 Tiger.prototype (kitty) → 找到 climb → **執行**
  3. 若仍未找到,繼續往 Object.prototype 找
  4. 最終到 null 結束,回傳 undefined

關鍵特性:

  • **查找是動態的**:修改 kitty.climb 會影響所有繼承實例
  • **寫入時建立自有屬性**:t.climb = function() {} 會在 t 上建立新屬性,**遮蔽** 原型鏈同名方法
  • **非複製**:方法不被複製到實例,節省記憶體

關鍵細節補充

1. kitty 也是有建構函式的

kitty.constructor === Object; // true
// 等同於:var kitty = new Object({ color: 'yellow', ... });

2. Object.prototype 是原型鏈終點

Object.prototype.__proto__ === null; // true

3. 建構函式 prototype 預設值

function Tiger() {}
Tiger.prototype; // { constructor: Tiger, __proto__: Object.prototype }

4. 重設 prototype 會遺失 constructor

Tiger.prototype = kitty;
var t = new Tiger();
t.constructor === Tiger; // false!
t.constructor === Object; // true (來自 kitty)

// 修正:手動恢復 constructor
Tiger.prototype = kitty;
Tiger.prototype.constructor = Tiger;

原型鏈 vs 類別繼承比較

特性原型鏈繼承ES6 class extends
語法手動設定 prototypeclass Child extends Parent
建構函式繼承需手動 Parent.call(this)自動呼叫 super()
靜態成員繼承Child.__proto__ = Parent自動繼承
方法定義位置Parent.prototype.method = ...class { method() {} }
底層機制完全相同語法糖,編譯為原型鏈

ES6 class 底層原型鏈示意

class Animal {
    constructor(name) { this.name = name; }
    speak() { console.log(this.name + '叫'); }
}

class Cat extends Animal {
    constructor(name, color) {
        super(name); // 必須先呼叫 super()
        this.color = color;
    }
    speak() { 
        super.speak(); // 呼叫父方法
        console.log('顏色:' + this.color);
    }
}

// 編譯後本質:
// Cat.prototype.__proto__ === Animal.prototype
// Cat.__proto__ === Animal

常見陷阱與最佳實務

❌ 陷阱:原型屬性共享參考型別

function Parent() {}
Parent.prototype.items = []; // 陣列被所有實例共享!

var a = new Parent();
var b = new Parent();
a.items.push(1);
console.log(b.items); // [1] - 意外共享!

解決:在建構函式初始化實例屬性 this.items = []

✅ 最佳實務:組合式繼承模式

function Parent(name) {
    this.name = name;
    this.items = []; // 實例自有陣列
}
Parent.prototype.sayName = function() { console.log(this.name); };

function Child(name, age) {
    Parent.call(this, name); // 繼承實例屬性
    this.age = age;
}
Child.prototype = Object.create(Parent.prototype); // 繼承原型方法
Child.prototype.constructor = Child;
Child.prototype.sayAge = function() { console.log(this.age); };

總結

原型鏈是 JavaScript 物件導向的靈魂。理解 prototype (建構函式屬性) 與 __proto__ (實例內部連結) 的區別、查找遞迴機制、寫入遮蔽行為,是掌握 JS 繼承、除錯原型污染、理解框架底層運作的關鍵。現代開發請直接使用 ES6 class,但底層原理不變。

copyright © 萬盛學電腦網 all rights reserved