JavaScript 透過原型鏈實現繼承與共享。將屬性與方法定義在建構函式的 prototype 上,所有實例皆可存取,節省記憶體並便於維護。
// 定義建構函式
function People(name, sex, age) {
this.name = name;
this.sex = sex;
this.age = age;
}
// 在 prototype 上共享屬性與方法
People.prototype = {
isStudent: true,
sayName: function() {
alert(this.name);
}
};
// 建立實例
var people1 = new People('韓梅梅', '女', 16);
var people2 = new People('李磊', '男', 17);
// 呼叫共享方法
people1.sayName(); // 彈出「韓梅梅」
people2.sayName(); // 彈出「李磊」
// 存取共享屬性
if (people1.isStudent === people2.isStudent) {
alert('他們都是學生');
}
People.prototype 被指派為一個物件字面量,其中的屬性與方法會被所有實例繼承。people1.isStudent = false),會遮蔽原型上的屬性,不影響其他實例。this 動態綁定至呼叫該方法的實例,故 sayName 能正確輸出各自名字。ES6 class 語法糖底層仍是原型,寫法更清晰:
class People {
constructor(name, sex, age) {
this.name = name;
this.sex = sex;
this.age = age;
}
sayName() { alert(this.name); }
}
// 靜態/共享屬性
People.prototype.isStudent = true;
善用 prototype 共享不變的屬性與方法,是 JavaScript 物件導向編程的基石,能有效減少記憶體佔用並保持程式碼結構清晰。