「組合模式」結合**建構函式定義實例屬性** + **原型定義共享方法/屬性**,是 ES5 時代最主流的繼承模式,兼顧實例獨立性與記憶體效率。
function Person(name, age, job) {
// 實例屬性:每個實例獨擁
this.name = name;
this.age = age;
this.job = job;
this.friends = ['Shelby', 'Court']; // 參考型別需在建構函式初始化,避免共享
}
// 共享方法定義在原型
Person.prototype = {
constructor: Person, // 修正 constructor 指向
sayName() {
console.log(this.name);
},
sayAge() {
console.log(this.age);
}
};
// 使用
const person1 = new Person('Jack', 25, 'Engineer');
const person2 = new Person('Karry', 30, 'Designer');
person1.friends.push('Tom');
console.log(person1.friends); // ['Shelby', 'Court', 'Tom']
console.log(person2.friends); // ['Shelby', 'Court'] (獨立)
console.log(person1.sayName === person2.sayName); // true (共享同一函式)
function inheritPrototype(SubType, SuperType) {
const prototype = Object.create(SuperType.prototype); // 建立超類原型副本
prototype.constructor = SubType; // 修正 constructor
SubType.prototype = prototype; // 指派給子類原型
}
function Super(name) {
this.name = name;
this.colors = ['red', 'blue'];
}
Super.prototype.sayName = function() { console.log(this.name); };
function Sub(name, age) {
Super.call(this, name); // 繼承實例屬性 (借用建構函式)
this.age = age;
}
inheritPrototype(Sub, Super); // 繼承原型方法
Sub.prototype.sayAge = function() { console.log(this.age); };
const sub = new Sub('Jack', 25);
sub.sayName(); // Jack
sub.sayAge(); // 25
sub.colors.push('green');
console.log(sub.colors); // ['red', 'blue', 'green'] (獨立)
class Person {
constructor(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
this.friends = ['Shelby', 'Court'];
}
sayName() { console.log(this.name); }
}
class Employee extends Person {
constructor(name, age, job, employeeId) {
super(name, age, job);
this.employeeId = employeeId;
}
sayId() { console.log(this.employeeId); }
}
組合模式 (建構函式 + 原型) 是 ES5 物件導向精髓。ES6 `class` 底層即此機制的語法糖。理解「實例屬性在建構函式、共享方法在原型」原則,即能正確設計繼承體系並避免共享參考型別 Bug。