學習 JavaScript 物件導向時,常會接觸到封裝、原型、繼承與多種建立物件模式。若只靠記憶,容易混淆。透過實作與圖解,能幫助理解。
ECMA-262 將物件定義為無序屬性的集合,屬性可以是基本值、物件或函式。每個物件都基於某個引用類型建立。
構造函數模式可用 new 建立實例。
function Person(name, age) {
this.name = name;
this.age = age;
this.sayName = function() {
console.log(this.name);
};
}使用 new 時,會建立新物件、指定構造函數作用域、執行構造函數,最後回傳新物件。
建立函式時,JavaScript 會為該函式建立 prototype 屬性。原型物件預設有 constructor 屬性,指向原函式。
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.country = 'chinese';
Person.prototype.sayCountry = function() {
console.log(this.country);
};實例會透過內部指針 linked to 原型,因此能共享原型上的屬性與方法。

若原型上有引用類型,所有實例可能共享同一份資料,這是常見陷阱。
實務上常把實例屬性放在構造函數,把方法放在原型。
function Person(name) {
this.name = name;
this.friends = [];
}
Person.prototype.sayName = function() {
console.log(this.name);
};這樣每個實例都有自己的 friends,而方法則共用,能兼顧記憶體與資料獨立。
讓子類別原型等於父類別實例,即可建立原型鏈。
function Parent() {
this.pname = 'parent';
}
Parent.prototype.getParentName = function() {
return this.pname;
};
function Child() {
this.cname = 'child';
}
Child.prototype = new Parent();
原型鏈的問題是,父類別中的引用類型可能被所有子實例共享。
組合繼承結合原型鏈與借用構造函數。原型鏈繼承方法,call 繼承屬性。
function Child(name) {
Parent.call(this, name);
this.age = 20;
}
Child.prototype = new Parent();這種方式能避免引用屬性共享,但會呼叫父構造函數兩次。
更理想的方式,是不呼叫父構造函數來建立子原型,而是複製父原型。
function extend(child, parent) {
function F() {}
F.prototype = parent.prototype;
child.prototype = new F();
child.prototype.constructor = child;
}這種方式只呼叫父構造函數一次,兼顧效能與資料獨立,是較完整的繼承實作。