var box = { name: 'lee', age: 100, run: function() { return this.name + this.age + '運行中...'; } };
console.log(box.run());
// 缺點:大量相似對象代碼重複,無類型標識
function createObject(name, age) {
var obj = new Object();
obj.name = name; obj.age = age;
obj.run = function() { return this.name + this.age + '運行中...'; };
return obj;
}
var box1 = createObject('lee', 100);
var box2 = createObject('jack', 200);
// 缺點:無法識別對象類型(typeof 皆為 Object)
function Box(name, age) {
this.name = name; this.age = age;
this.run = function() { return this.name + this.age + '運行中...'; };
}
var box1 = new Box('lee', 100);
var box2 = new Box('jack', 200);
console.log(box1 instanceof Box); // true
// 缺點:每個實例擁有獨立 run 函數,內存浪費
function Box() {}
Box.prototype.name = 'Lee';
Box.prototype.age = 100;
Box.prototype.run = function() { return this.name + this.age + '運行中...'; };
var box1 = new Box();
var box2 = new Box();
console.log(box1.run === box2.run); // true,共享同一函數引用
__proto__ 找構造函數 prototypeObject.prototype,最後 null__proto__:實例指向原型的內部指針(IE 不支援直接訪問)constructor:原型指回構造函數isPrototypeOf():判斷原型鏈關係hasOwnProperty(prop):判斷屬性是否在實例自身in 操作符:實例或原型鏈中存在即返回 truebox1.name = 'Jack'; // 實例新增 name,遮蔽原型 name
delete box1.name; // 刪除實例屬性,恢復讀取原型值
function Box(name, age) {
this.name = name; this.age = age; // 實例屬性(私有)
}
Box.prototype = {
constructor: Box, // 修正 constructor 指向
run: function() { return this.name + this.age + '運行中...'; },
say: function() { console.log('hello'); }
};
(篇幅所限略過,核心思想:延遲初始化原型、封裝私有變量、無 this 依賴)
| 模式 | 核心思想 | 缺點 |
|---|---|---|
| 原型鏈繼承 | Child.prototype = new Parent() | 引用類型屬性共享、無法向父傳參 |
| 借用構造函數 | Parent.call(this, args) | 方法無法復用(在構造函數內定義) |
| 組合繼承 | 原型鏈繼承方法 + 借用構造函數繼承屬性 | 調用兩次父構造函數 |
| 原型式繼承 | Object.create(proto) | 同原型鏈,引用類型共享 |
| 寄生式繼承 | 創建對象→增強→返回 | 方法無法復用 |
| 寄生組合式繼承 | Object.create(Parent.prototype) + 借用構造函數 | **最佳實踐**(ES5) |
class Box {
constructor(name, age) { this.name = name; this.age = age; }
run() { return this.name + this.age + '運行中...'; }
static createDefault() { return new Box('default', 0); } // 靜態方法
}
class SpecialBox extends Box {
constructor(name, age, power) {
super(name, age); // 必須先調用 super()
this.power = power;
}
run() { return super.run() + ' [增強版]'; } // 覆寫並調用父方法
}
理解「構造函數 + 原型」是 JS 面向對象的基石。實戰中:
__proto__,改用 Object.getPrototypeOf/Object.setPrototypeOfObject.create(null) 創建純字典對象,避免原型污染