前言
JavaScript 是基於**原型繼承** 的物件導向語言,而非類別繼承。雖然 ES6 引入 class 語法糖,但底層機制仍是 Prototype。深入理解原型鏈、建構函式、this 綁定、繼承模式,是寫出高階 JS 程式碼、閱讀框架原始碼、解決疑難雜症的關鍵。
核心概念速查
| 概念 | 說明 | 關鍵點 |
| Prototype (原型) |
物件的隱藏屬性 [[Prototype]],指向另一個物件 |
所有物件 (除 Object.create(null)) 都有原型 |
| Prototype Chain (原型鏈) |
透過 [[Prototype]] 串連形成的查找路徑 |
屬性存取時沿鏈向上查找,直到 null |
| Constructor (建構函式) |
配合 new 建立實例的函式 |
慣例大寫開頭,prototype 屬性指向實例的原型 |
__proto__ |
實例存取原型的非標準屬性 (現已標準化) |
obj.__proto__ === Constructor.prototype |
prototype |
建構函式的屬性,指向實例共享的原型物件 |
方法、共享屬性定義在這裡 |
三種建立物件模式演進
1. 工廠模式 (Factory Pattern) - 解決重複建立
function createPerson(name, age) {
const obj = new Object();
obj.name = name;
obj.age = age;
obj.sayName = function() {
console.log(this.name);
};
return obj;
}
const p1 = createPerson('Alice', 25);
const p2 = createPerson('Bob', 30);
// 缺點:無法識別物件類型 (都是 Object),sayName 每個實例各有一份 (記憶體浪費)
2. 建構函式模式 (Constructor Pattern) - 解決類型識別
function Person(name, age) {
this.name = name;
this.age = age;
// 缺點:方法仍在建構函式內定義,每個實例各有一份
this.sayName = function() {
console.log(this.name);
};
}
const p1 = new Person('Alice', 25);
const p2 = new Person('Bob', 30);
console.log(p1 instanceof Person); // true
console.log(p1.constructor === Person); // true
console.log(p1.sayName === p2.sayName); // false (每個實例獨立函式)
3. 原型模式 (Prototype Pattern) - 解決方法共享
function Person(name, age) {
this.name = name;
this.age = age;
}
// 方法定義在 prototype 上,所有實例共享
Person.prototype.sayName = function() {
console.log(this.name);
};
Person.prototype.species = 'Human'; // 共享屬性 (引用類型需謹慎)
const p1 = new Person('Alice', 25);
const p2 = new Person('Bob', 30);
console.log(p1.sayName === p2.sayName); // true (共享同一函式)
console.log(p1.hasOwnProperty('name')); // true (實例自有屬性)
console.log('species' in p1); // true (原型鏈上有)
4. 組合模式 (業界標準:建構函式定義實例屬性 + Prototype 定義方法)
function Person(name, age) {
// 實例屬性:每個實例獨有
this.name = name;
this.age = age;
this.friends = ['Mike']; // 引用類型必須在建構函式初始化,避免共享
}
// 方法與共享屬性定義在 prototype
Person.prototype = {
constructor: Person, // 修正 constructor 指向
sayName() {
console.log(this.name);
},
sayAge() {
console.log(this.age);
}
};
// ES5 寫法補充:Object.create 建立繼承鏈
function Student(name, age, grade) {
Person.call(this, name, age); // 繼承實例屬性 (借用建構函式)
this.grade = grade;
}
// 原型繼承
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
Student.prototype.study = function() { console.log('Studying...'); };
原型鏈查找機制圖解
p1 (Student 實例)
│
├── name: 'Alice' (自有屬性)
├── age: 20 (自有屬性)
├── grade: 3 (自有屬性)
│
▼ [[Prototype]] (Student.prototype)
│
├── constructor: Student
├── study: ƒ()
│
▼ [[Prototype]] (Person.prototype)
│
├── constructor: Person
├── sayName: ƒ()
├── sayAge: ƒ()
│
▼ [[Prototype]] (Object.prototype)
│
├── toString: ƒ()
├── hasOwnProperty: ƒ()
│
▼ null (原型鏈終點)
屬性讀取:沿原型鏈向上查找,找到即回傳
屬性寫入:永遠在實例上建立/遮蔽,不會修改原型
刪除屬性:delete obj.prop 僅刪除自有屬性,原型屬性不受影響
this 綁定規則 (關鍵!)
| 呼叫方式 | this 指向 | 範例 |
| 預設綁定 |
全域物件 (非嚴格模式) / undefined (嚴格模式) |
func() |
| 隱式綁定 |
呼叫者物件 |
obj.method() |
| 明確綁定 |
指定物件 |
func.call(obj), apply, bind |
| new 綁定 |
新建立的實例 |
new Constructor() |
| 箭頭函式 |
詞法作用域的 this (定義時外層 this) |
() => this |
ES6 Class 語法糖與底層對應
// ES6 Class
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayName() { console.log(this.name); }
static species = 'Human'; // 靜態屬性 (ES2022)
}
// 底層等價於:
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.sayName = function() { console.log(this.name); };
Person.species = 'Human'; // 靜態屬性掛在建構函式上
// 繼承
class Student extends Person {
constructor(name, age, grade) {
super(name, age); // 必須先呼叫 super()
this.grade = grade;
}
study() { console.log('Studying...'); }
}
// 底層:
function Student(name, age, grade) {
Person.call(this, name, age);
this.grade = grade;
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
Student.prototype.study = function() { console.log('Studying...'); };
常見陷阱與最佳實踐
| 陷阱 | 錯誤代碼 | 正確做法 |
| 原型共享引用類型屬性 |
Person.prototype.friends = [] |
引用類型在建構函式初始化:this.friends = [] |
忘記修正 constructor |
Child.prototype = Object.create(Parent.prototype) 導致 constructor 指向 Parent |
手動修正:Child.prototype.constructor = Child |
| 箭頭函式用作方法 |
sayName = () => console.log(this.name) 在 prototype 上 |
箭頭函式無自有 this,會捕獲外層 (通常是 window),改用一般函式 |
繼承未呼叫 super() |
class Child extends Parent { constructor() {} } |
子類別建構函式必須呼叫 super() 才能使用 this |
| 修改內建原型 |
Array.prototype.myMethod = ... |
汙染全域環境,衝突風險極高,禁止修改內建原型 |
Object.create(null):純字典物件
const dict = Object.create(null); // 無原型,無 toString、hasOwnProperty 等
dict['key'] = 'value';
// 安全儲存鍵值對,無原型鏈干擾,適合 Map-like 用途
總結
- JS 物件導向核心是 **Prototype 委派機制**,而非類別複製
- 組合模式 (建構函式 + Prototype) 是經典最佳實踐
- ES6
class 是語法糖,底層仍是原型鏈,**必須理解底層才能駕馭進階用法**
this 由呼叫方式決定,箭頭函式捕獲詞法作用域 this
- 繼承本質:
Child.prototype = Object.create(Parent.prototype) 建立原型鏈
- 避免修改內建原型,引用類型屬性放在建構函式初始化