核心概念
- 原型鏈查找:讀取屬性時,先找實例自有屬性 → 找不到沿 `__proto__` 找構造函數 `prototype` → 再找 `Object.prototype` → `null`。
- 寫入屬性:**永遠在實例上創建/修改自有屬性**,**不會**修改原型對象的屬性(除非用 `Object.defineProperty` 在原型上定義 setter)。
- 引用類型共享**:原型上定義的對象/數組被所有實例共享,修改其**內容**(`push`、修改屬性)會影響所有實例;**重新賦值**(`=`)則在實例上創建新屬性,切斷共享。
代碼驗證:值類型屬性
function Person() {}
Person.prototype = {
constructor: Person,
name: "person",
age: 100,
getName: function() { return this.name; }
};
var p1 = new Person();
var p2 = new Person();
console.log(p1.name); // "person" (來自原型)
console.log(p2.name); // "person"
p1.name = "p1"; // 在 p1 上創建自有屬性 name,遮蔽原型
console.log(p1.name); // "p1"
console.log(p2.name); // "person" (原型未變)
console.log(p1.hasOwnProperty("name")); // true
console.log(p2.hasOwnProperty("name")); // false
console.log(Object.keys(p1)); // ["name"]
console.log(Object.keys(p2)); // []
console.log(Person.prototype.name); // "person" (原型未被修改)
代碼驗證:引用類型屬性(數組)
Person.prototype.friends = ["a", "b"];
var p1 = new Person();
var p2 = new Person();
p1.friends.push("c"); // 修改共享數組內容
console.log(p1.friends); // ["a", "b", "c"]
console.log(p2.friends); // ["a", "b", "c"] ← 受影響!
console.log(Person.prototype.friends); // ["a", "b", "c"]
p1.friends = ["x", "y", "z"]; // 重新賦值 → p1 自有屬性遮蔽原型
console.log(p1.friends); // ["x", "y", "z"]
console.log(p2.friends); // ["a", "b", "c"] (原型數組未變)
console.log(p1.hasOwnProperty("friends")); // true
console.log(p2.hasOwnProperty("friends")); // false
原理圖解
初始狀態:
p1 ──────► Person.prototype ──────► Object.prototype
{ friends: ["a","b"] }
p1.friends.push("c") 後:
p1 ──────► Person.prototype ──────► Object.prototype
{ friends: ["a","b","c"] } ← 同一個數組對象
p1.friends = ["x","y","z"] 後:
p1 ──────► { friends: ["x","y","z"] } (自有屬性)
│
└──► Person.prototype ──────► Object.prototype
{ friends: ["a","b","c"] } (原型保持不變)
最佳實踐原則
- 不可變數據放原型:字符串、數字、布爾、函數(方法)安全共享。
- 可變數據(對象/數組)放構造函數內實例化:
function Person(name) {
this.name = name;
this.friends = []; // 每個實例擁有獨立數組
}
- 需共享狀態時刻意設計**:如單例、緩存、事件總線,明確文檔標註。
- ES6 Class 寫法自動避免此坑**:
class Person {
constructor(name) {
this.name = name;
this.friends = []; // 實例自有
}
getName() { return this.name; } // 方法定義在 prototype 上
}
Object.defineProperty 在原型定義存取器(進階)
var obj = {};
Object.defineProperty(obj, "name", {
get: function() { return this._name; },
set: function(v) { this._name = v.toUpperCase(); }
});
var child = Object.create(obj);
child.name = "alice"; // 觸發原型上的 setter
console.log(child._name); // "ALICE" (寫入子對象自有屬性 _name)
console.log(obj._name); // undefined (原型無 _name)
總結
- **讀取**沿原型鏈,**寫入**只在實例。
- 原型上的引用類型屬性是**共享的**,修改內容影響所有實例。
- 實例賦值同名屬性會**遮蔽**原型屬性,而非修改它。
- 構造函數中初始化可變屬性,方法放 `prototype`,完美解決共享問題。