JS 無「類」概念,但可透過多種模式模擬面向對象。本文由淺入深梳理 6 種創建物件模式,分析優缺點與演進邏輯。
var obj = { name: 'Koji', age: 21, sayHi: function() { console.log(this.name); } };
// 缺點:需重複代碼創建多個相似物件
function createPerson(name, age) {
return { name: name, age: age, sayHi: function() { console.log(this.name); } };
}
var p1 = createPerson('Koji', 22);
var p2 = createPerson('Luo', 21);
解決復用,但無法識別物件類型(皆為 Object),且每個實例擁有獨立函數副本,浪費記憶體。
function Person(name, age) {
this.name = name;
this.age = age;
this.sayHi = function() { console.log(this.name); }; // 仍在構造函數內定義方法
}
var p1 = new Person('Koji', 22);
new 操作:建立新物件 → this 指向新物件 → 執行函數體 → 返回 this。
缺點:方法仍為每實例獨享。
function Person() {}
Person.prototype.name = 'Koji';
Person.prototype.sayHi = function() { console.log(this.name); };
var p1 = new Person(); // 共享 prototype 上的屬性/方法
優點:方法共享。
缺點:引用類型屬性(陣列、物件)會被所有實例共享,修改一處影響全體。
function Person(name, age) {
this.name = name; // 實例屬性(私有)
this.age = age;
this.friends = ['A', 'B']; // 引用類型也在構造函數定義,保證私有
}
Person.prototype.sayHi = function() { console.log(this.name); }; // 方法共享
Person.prototype.sayAge = function() { console.log(this.age); };
實現屬性私有、方法共享,兼顧記憶體與隔離性。
視專案複雜度選用,現代開發多直接採用 class 語法糖(ES6),底層仍是組合模式。
class Person {
constructor(name, age) { this.name = name; this.age = age; this.friends = []; }
sayHi() { console.log(this.name); }
}