原型鏈是 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() 時:
t 自有屬性 → 無__proto__ 找 Tiger.prototype (kitty) → 找到 climb → **執行**Object.prototype 找null 結束,回傳 undefined關鍵特性:
kitty.climb 會影響所有繼承實例t.climb = function() {} 會在 t 上建立新屬性,**遮蔽** 原型鏈同名方法kitty 也是有建構函式的kitty.constructor === Object; // true
// 等同於:var kitty = new Object({ color: 'yellow', ... });
Object.prototype 是原型鏈終點Object.prototype.__proto__ === null; // true
prototype 預設值function Tiger() {}
Tiger.prototype; // { constructor: Tiger, __proto__: Object.prototype }
prototype 會遺失 constructorTiger.prototype = kitty;
var t = new Tiger();
t.constructor === Tiger; // false!
t.constructor === Object; // true (來自 kitty)
// 修正:手動恢復 constructor
Tiger.prototype = kitty;
Tiger.prototype.constructor = Tiger;
| 特性 | 原型鏈繼承 | ES6 class extends |
|---|---|---|
| 語法 | 手動設定 prototype | class Child extends Parent |
| 建構函式繼承 | 需手動 Parent.call(this) | 自動呼叫 super() |
| 靜態成員繼承 | Child.__proto__ = Parent | 自動繼承 |
| 方法定義位置 | Parent.prototype.method = ... | class { method() {} } |
| 底層機制 | 完全相同 | 語法糖,編譯為原型鏈 |
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,但底層原理不變。