function createPerson(name, age) {
var o = new Object();
o.name = name;
o.age = age;
o.sayName = function() { console.log(this.name); };
return o;
}
var p1 = createPerson('Jack', 20);
缺點:無法識別對象類型(都是 Object 實例)。
function Person(name, age) {
this.name = name;
this.age = age;
this.sayName = function() { console.log(this.name); }; // 每個實例創建新函數
}
var p1 = new Person('Jack', 20);
var p2 = new Person('Rose', 18);
console.log(p1.sayName === p2.sayName); // false — 方法不共享,浪費內存
function Person(name, age) {
this.name = name; // 實例屬性
this.age = age;
}
Person.prototype.sayName = function() { // 共享方法
console.log(this.name);
};
Person.prototype.species = 'Human'; // 共享屬性
var p1 = new Person('Jack', 20);
var p2 = new Person('Rose', 18);
console.log(p1.sayName === p2.sayName); // true — 共享同一函數
p1.colors = ['red']; // 實例屬性覆蓋原型屬性(遮蔽)
console.log(p1.colors); // ['red']
console.log(p2.colors); // undefined (原型無此屬性)
prototype 屬性指向一個對象(原型對象),該對象包含 constructor 指回構造函數。
Person.prototype.constructor === Person; // true
[[Prototype]](__proto__)指向構造函數的 prototypep1.__proto__ === Person.prototype; // true
Person.prototype.__proto__ === Object.prototype; // true
Object.prototype.__proto__ === null; // 鏈終點
hasOwnProperty 為 true)__proto__ 向上查找)Object.prototype 內置屬性(toString、valueOf 等)undefineddelete obj.prop 只刪除實例屬性,恢復原型屬性可見性。Person.prototype = {
sayName: function() { console.log(this.name); },
sayAge: function() { console.log(this.age); }
};
// 問題:constructor 指向 Object,而非 Person
console.log(Person.prototype.constructor === Person); // false
console.log(Person.prototype.constructor === Object); // true
// 修正
Person.prototype = {
constructor: Person, // 手動指回
sayName: function() { ... },
sayAge: function() { ... }
};
function Person(name, age) {
this.name = name;
this.age = age;
if (typeof this.sayName !== 'function') { // 只初始化一次
Person.prototype.sayName = function() { console.log(this.name); };
}
}
var p1 = new Person('Jack', 20);
p1.sayName(); // 正常
優點:封裝性好,所有信息在構造函數內。缺點:無法重寫整個原型對象(會切斷已有實例連結)。
function Person(name, age) {
var o = new Object();
o.name = name;
o.age = age;
o.sayName = function() { console.log(this.name); };
return o; // 手動返回對象
}
var p1 = new Person('Jack', 20); // p1 實際是 Object 實例,非 Person 實例
console.log(p1 instanceof Person); // false
適用於特殊情況(如需返回特定類型對象),但失去 instanceof 識別能力。
function Person(name, age) {
var o = new Object(); // 或 Object.create(null)
o.sayName = function() { console.log(name); }; // 閉包訪問私有變量
return o;
}
var p1 = Person('Jack', 20); // 不用 new
p1.sayName(); // Jack
// 無 this、無原型、無公共屬性,極高安全性,但無法識別類型、方法不共享
| 模式 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| 構造函數+原型 | 方法共享、instanceof正常、支援傳參 | 代碼分散在兩處 | 最通用、推薦 |
| 動態原型 | 封裝性好、單次初始化 | 不可重寫整個原型 | 庫作者、需封裝 |
| 寄生構造函數 | 可返回任意類型 | 失去instanceof | 特殊封裝需求 |
| 穩妥構造函數 | 真私有變量、安全 | 無原型、無類型識別、方法不共享 | 高安全環境 |
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayName() { console.log(this.name); } // 自動定義在 Person.prototype 上
}
const p1 = new Person('Jack', 20);
// 底層依然是構造函數+原型機制,理解原型鏈對調試、繼承、性能優化至關重要