這篇整理偏長,建議先收藏再慢慢看。
var person = new Object(); 變數 person 裡存的是這個物件在記憶體堆中的位址。順帶一提,JavaScript 這類高階語言無法直接以程式碼存取物理記憶體,需透過腳本擴充介面繞道,這裡先擱著,之後再深入。Object 是所有其他物件的基礎,Object 具備的屬性與方法,更具體的物件也都能用。

JavaScript 主要靠原型鏈完成「實現繼承」。每次建立實例時,該實例便繼承了 Object.prototype 上的方法;但這種繼承並非複製一份副本,而是指向同一個位置的引用式繼承。
person.constructor; // function Object() { [native code] }person.hasOwnProperty('constructor'); // false
Object.prototype.hasOwnProperty('constructor'); // trueObject.prototype.isPrototypeOf(person); // truevar number = 10; number.toString(); // "10"
var str = 'xx'; str.toString(); // "xx"
var person = new Object(); person.toString(); // "[object Object]"
var a = new Array(); a.toString(); // "",等同逐項 toString 後拼接
new Function('console.log(1)').toString(); // "function anonymous() {console.log(1)}"
new Number(10).toString(); // "10"
基本型別回傳的是副本,修改原變數不影響已取出的字串。var num = 1; var numnew = num.valueOf(); num += 2; // num=3, numnew=1 new Number().valueOf(); // 0 new String().valueOf(); // "" Object.valueOf() == Object; // true var o = new Object(); o.valueOf() == o; // true

var o = new Object();
o.name = "xx";
o.say = function () { console.log('hi'); }
// 不傳參數時可省略括號,但不建議var o = {
name: 'xx',
say: function () { console.log('hi'); }
}
在表達式上下文中,左花括號代表物件字面量的起點;若同樣的括號跟在 if 之後,則是語句區塊的起點。用字面量建立物件時,實際上並不會呼叫 Object 建構函式。屬性名可加引號也可簡寫,引擎會自動轉為字串:
for (var i in o) { console.log(typeof i); } // string
字面量也是傳遞大量可選參數的首選方式:
function displayInfo(args) {
var output = "";
for (var i in args) {
if (args.hasOwnProperty(i)) {
if (typeof args[i] == 'function') { output += args[i](); }
else { output += args[i] + ' '; }
}
}
console.log(output);
}
displayInfo({ name: 'xx', say: function () { return 'hi'; } });
另外,當屬性名含有會造成語法錯誤的字元,或本身就是保留字時,就必須改用中括號寫法,把屬性名以字串形式放進去;中括號的另一個好處是可以透過變數動態取用屬性。
Object 建構函式與字面量都能建立單一物件,但用同一組介面大量產生物件時,會湧現可觀的重複程式碼。於是有了以下七種模式。
用函式封裝建立物件的細節,只對外提供介面——這其實就是軟體工程裡常見的封裝手法。
function createPerson(name, age, job) {
var o = new Object();
o.name = name; o.age = age; o.job = job;
o.say = function () { console.log(this.name); };
return o;
}
var person1 = createPerson('xx', 20, 'student');
var person2 = createPerson('mm', 22, 'student');
person1 == person2; // false
缺點:沒有解決物件識別問題。你能用 person1.__proto__ 之類的手段試探,卻無法直觀知道 person1 是哪種類型的實例。
function Person(name, age, job) {
this.name = name; this.age = age; this.job = job;
this.say = function () { console.log(this.name); };
}
var p1 = new Person('xx', 20, 'student');
var p2 = new Person('mm', 22, 'student');
p1 == p2; // false
p1.constructor == Person; // true
與工廠模式相比,這裡沒有顯式建立物件、直接把屬性掛在 this 上、也沒有 return。慣例上建構函式以我也不會大寫開頭,一般函式小寫開頭,沿用其他 OO 語言的習慣以便區分。
用 new 呼叫建構函式,實際會經歷四步:
p1 與 p2 上的 constructor 嚴格說並非自身屬性,而是沿原型鏈繼承而來。由於原型鏈的關係,p1 同時是 Object 與 Person 的實例:
p1 instanceof Object; // true p1 instanceof Person; // true
能明確標識實例類型,正是建構函式勝過工廠模式之處。你也可以在別的物件作用域中呼叫它:
var o = new Object(); Person.call(o, 'xx', 20, 'student'); o.say(); // xx
缺點:say 方法要在每個實例上各建一份,p1.say == p2.say 為 false。把函式獨立出來可以解決:
function Person(name, age, job) {
this.name = name; this.age = age; this.job = job;
this.say = say;
}
function say() { console.log(this.name); }
但這又帶來兩個新問題:全域函式只有被特定物件呼叫時才有意義,名不副實;方法一多,全域函式就跟著暴增,封裝性蕩然無存。
每個函式都有一個 prototype 屬性,指向一個物件。這個原型物件的用途,就是容納特定類型所有實例共享的屬性與方法。
function Person() {}
Person.prototype.name = 'xx';
Person.prototype.age = 29;
Person.prototype.job = "student";
Person.prototype.say = function () { console.log(this.name); };
var p1 = new Person();
p1.name; // 'xx'
var p2 = new Person();
p1 == p2; // false
p1.say == p2.say; // true
'job' in p1; // truefor-in 回傳所有可列舉的屬性(實例與原型皆然)。Object.prototype 上的屬性 enumerable 預設為 false,因此不會被列出。但實例上自訂的同名方法可以覆蓋這種不可列舉性。
var p = { name: 'xx', say: function () {} };
Object.getOwnPropertyDescriptor(p, 'name');
// { value: "xx", writable: true, enumerable: true, configurable: true }
var o = new Object(); o.name = 'xx';
Object.getOwnPropertyDescriptor(o, 'name');
// { value: "xx", writable: true, enumerable: true, configurable: true }
var p2 = {};
Object.defineProperty(p2, 'name', { value: 'xx' });
Object.getOwnPropertyDescriptor(p2, 'name');
// { value: "xx", writable: false, enumerable: false, configurable: false }
注意:以 defineProperty 定義後,若未顯式宣告 writable 為 true,就不能再用同樣方式重新定義。另外,覆寫 toString 這類繼承而來的方法,在早期 IE 會失效,因為 IE 認為原型上的 toString 帶有 enumerable=false 標記而跳過它。解法有兩個:
// 解法一:改變可列舉性
Object.defineProperty(Object.prototype, "valueOf", { enumerable: true });
Object.defineProperty(o, "valueOf", { enumerable: true });
// 解法二:用 getOwnPropertyNames 取得全部自身屬性名,不論是否可列舉 Object.getOwnPropertyNames(Person.prototype); // ["constructor", "name", "age", "job", "say"] // ES5 的 Object.keys 只取「物件自身」可列舉的屬性,省去 for-in + hasOwnProperty 的篩選 Object.keys(Person.prototype); // ["name", "age", "job", "say"]
更簡潔的原型語法:用字面量整體重寫原型。
Person.prototype = {
name: 'xx',
age: 22,
say: function () { console.log(this.name); },
constructor: Person
}
這種寫法會讓原本的 constructor 消失,因為 prototype 被指向了別的物件,而每個函式建立時自動掛上 constructor 的那個原型物件就再也沒人引用。有趣的是,此時 Person.prototype.constructor 仍讀得到東西——那是沿原型鏈從 Object.prototype 繼承來的,已經不能用來判斷實例類型:
Person.prototype.hasOwnProperty('constructor'); // false
Object.prototype.hasOwnProperty('constructor'); // true
若仍需要 constructor,可以手動補回去,但接著得再用 Object.defineProperty 把它的 enumerable 特性改回 false。
原型的動態性:實例與原型之間只是一個指針,不是副本,所以之後掛到原型上的方法,既有實例也能立刻用到。但一旦你「整體替換」原型物件,順序就變得至關重要:實例建立時記下的是當時那個原型,之後換掉 Person.prototype,實例的 __proto__ 與 Person.prototype 便指向不同物件,訪問自然出錯。

原生物件(Object、Array、String 等)的原型同樣可以擴充,但不建議這麼做,容易與其他程式碼或未來版本命名衝突。
原型模式的問題:它省略了向建構函式傳參的能力,所有實例預設拿到相同的值。共享對函式很合適,但對「值為引用類型」的屬性就是災難:
function Person() {}
Person.prototype = { constructor: Person, name: 'xx', hobby: ['a', 'b'] };
var p1 = new Person();
var p2 = new Person();
p1.hobby.push('c');
p1.hobby; // ['a','b','c']
p2.hobby; // ['a','b','c'] —— 被連帶改掉了
最常見的折衷:實例屬性放建構函式,方法與共享屬性放原型。每個實例擁有自己那份屬性副本,同時共享方法引用,省記憶體。
function Person(name, age) {
this.name = name; this.age = age; this.hobby = ['a', 'b'];
}
Person.prototype = {
constructor: Person,
say: function () { console.log(this.name); }
}
var p1 = new Person('xx', 20);
var p2 = new Person('mm', 20);
p1.hobby.push('c');
p2.hobby; // ['a','b']
把資訊全部封裝在建構函式內,只在必要時初始化原型,兼顧封裝性與共用方法的優點。
function Person(name, age) {
this.name = name; this.age = age;
if (typeof this.say != 'function') {
Person.prototype.say = function () { console.log(this.name); };
}
}
var f = new Person("xx", 20);
f.say(); // 'xx'
if 判斷的內容可以是初始化後應該存在的任何屬性或方法,只需檢查其中一個即可,不必逐一判斷。
缺點:不能用字面量整體重寫原型,因為實例先於原型修改建立。

工廠模式與建構函式的結合,除了使用 new 並把包裝函式當建構函式看,本質與工廠模式相同。這裡牽涉到建構函式的回傳值規則:
function Person(name, age) {
var o = new Object();
o.name = name; o.age = age;
o.say = function () { console.log(this.name); };
return o;
}
var p = new Person('xx', 20);
p.say();
典型應用:想替特殊陣列加上額外方法,而 Array 建構函式又不便直接改寫。
function SpecialArray() {
var values = new Array();
values.push.apply(values, arguments);
values.toPipedString = function () { return values.join('|'); };
return values;
}
var hobbits = new SpecialArray('a', 'b', 'c');
hobbits.toPipedString(); // "a|b|c"
要注意:回傳的物件與建構函式或其原型沒有任何關聯,因此不能用 instanceof 判斷類型。不推薦。
穩妥物件沒有公共屬性,方法也不引用 this,最適合禁止使用 this 與 new 的安全環境。
function Person(name, age) {
var o = new Object();
// 此處可定義私有變數與函式
o.say = function () { console.log(name); };
return o;
}
var p = Person('xx', 20);
p.say(); // 'xx'
這種物件除了 say 之外沒有別的方法能讀到建構時傳入的資料,即使外部替它掛上新方法也一樣。它與建構函式之間同樣沒有關聯,不能用 instanceof 判斷。
多數 OO 語言支援兩種繼承:接口繼承只繼承方法簽名,實現繼承繼承實際方法。ECMAScript 的函式沒有簽名,因此只支援實現繼承,且主要透過原型鏈完成。
基本做法是讓原型物件等於另一個類型的實例,於是這個原型就帶有一個指向另一個原型的指針,層層遞進便形成實例與原型的鏈條。
function SuperType() { this.property = true; }
SuperType.prototype.getSuperValue = function () { return this.property; }
function SuberType() { this.subproperty = false; }
SuberType.prototype = new SuperType();
SuberType.prototype.getSubValue = function () { return this.subproperty; }
var instance = new SuberType();
instance.getSuperValue(); // true
呼叫 getSuperValue 時依序搜尋:實例 → SuberType.prototype → SuperType.prototype,最後一步才找到。
instance instanceof Object; // true instance instanceof SuperType; // true instance instanceof SuberType; // true Object.prototype.isPrototypeOf(instance); // true SuperType.prototype.isPrototypeOf(instance); // true
在子類建構函式中呼叫超類建構函式,透過 apply / call 在新物件上執行它。
function SuperType() { this.colors = ["a", "b"]; }
function SuberType() { SuperType.call(this); }
var instance1 = new SuberType();
instance1.colors.push('c'); // ["a","b","c"]
var instance2 = new SuberType();
instance2.colors; // ["a","b"]
優點是可以傳參:
function SuperType(name) { this.name = name; }
function SuberType(age) {
SuperType.call(this, "xx");
this.age = age; // 子類屬性要寫在呼叫之後,才不會被覆蓋
}
var instance = new SuberType(20);
instance.name; // "xx"
缺點:方法都定義在建構函式裡,無法複用,超類原型上的方法對子類不可見。也很少單獨使用。
原型鏈繼承原型屬性與方法,借用建構函式繼承實例屬性,是最常出現的寫法。
function SuperType(name) {
this.name = name;
this.colors = ["a", "b"];
}
SuperType.prototype.sayName = function () { console.log(this.name); };
function SuberType(name, age) {
SuperType.call(this, name);
this.age = age;
}
SuberType.prototype = new SuperType();
SuberType.prototype.constructor = SuberType;
SuberType.prototype.sayAge = function () { console.log(this.age); };
var a1 = new SuberType('xx', 20);

a1.colors.push('c');
a1.colors; // ["a","b","c"]
a1.sayAge(); // 20
a1.sayName(); // xx

缺點:超類建構函式被呼叫了兩次——一次在建立子類原型時,一次在子類建構函式內。子類原型上因此留下一堆用不到的屬性,而這些屬性又會在子類建構時被重新覆寫。解法是寄生組合式繼承。
不借助嚴格意義上的建構函式,而是基於既有物件產生新物件。
function object(o) {
function F() {}
F.prototype = o;
return new F();
}
var person = { name: "xx", friends: ["aa", "bb", "cc"] };
var p1 = object(person);
p1.name; // "xx"
p1.name = "xixi";
p1.friends.push("dd");
person.friends; // ["aa","bb","cc","dd"] —— 引用類型被共享
var p2 = object(person);
p2.friends.push("ee");
person.friends; // ["aa","bb","cc","dd","ee"]
ES5 的 Object.create() 把它標準化了,第一個參數作為新物件的原型,第二個(可選)參數用來定義額外屬性:
var p1 = Object.create(person, { name: { value: "xixi" } });
p1.name; // "xixi"
person.name; // "xx"
第二個參數的格式與 Object.defineProperties() 相同,每個屬性都由自己的描述符定義,並會覆蓋原型上的同名屬性。
缺點:含引用類型的屬性永遠是共享的。
與原型式繼承關係密切,做法是寫一個只負責封裝繼承流程的函式,在內部增強物件後回傳。
function createAnother(original) {
var clone = object(original);
clone.say = function () { console.log("hi"); };
return clone;
}
var p1 = createAnother({ name: 'xx', friends: ["aa", "bb", "cc"] });
p1.say(); // hi
任何能回傳新物件的函式都能勝任,object() 並非必要。
缺點:函式是掛在物件上的,無法複用。
我們真正需要的其實只是「超類原型的一個副本」,而不是為了指定子類原型就把超類建構函式跑一遍。結合寄生式繼承正好能做到這件事。
function inheritPrototype(suberType, superType) {
var prototype = object(superType.prototype); // 建立物件
prototype.constructor = suberType; // 增強物件
suberType.prototype = prototype; // 指定物件
}
function SuperType(name) {
this.name = name;
this.colors = ["aa", "bb", "cc"];
}
SuperType.prototype.say = function () { console.log(this.name); };
function SuberType(age, name) {
SuperType.call(this, name);
this.age = age;
}
inheritPrototype(SuberType, SuperType);
SuberType.prototype.say = function () { console.log(this.age); };
只呼叫一次父類建構函式,效率更好,instanceof 與 isPrototypeOf 也能正常使用,是引用類型最理想的繼承范式。YUI 的 YAHOO.lang.extend 採用的正是這種做法。

參考:《JavaScript 高階程式設計》