JavaScript 是一門極具彈性的腳本語言,與 Java、C++ 這類需要編譯執行、有明確型別結構的語言差異很大,學習過程中也因此容易產生困惑。有四個概念必須先弄清楚:prototype、execution、context、closure。本文先從 prototype 談起。
Object、String、Date 這些「內建型別」在 JS 裡其實是函式名稱。執行 alert(typeof Object) 會輸出 "function",可以驗證。我們平常說的「Date 型別的資料」,嚴格講是 new Date 所產生的那個物件。__proto__ 屬性檢視一個物件的 prototype。function Person() {
this.age = 10;
this.name = "test";
}
Person.prototype = new Object;
var p = new Person;
alert(p); // "[object Object]"
alert(p.__proto__); // "[object Object]"
Person 有一個 prototype,而改動它會同時影響已產生的實例與之後才建立的實例。這是 prototype 最重要的特性:它是所有實例共享的一張掛牌。
一般說「JS 物件都繼承 Object」,這句話在程式碼裡長什麼樣?
function Person() {
this.age = 10;
this.name = "test";
}
var p = new Person;
alert(p.__proto__.__proto__ == Object.prototype); // true
alert(p.__proto__.__proto__.__proto__); // null
Person 未明確指定 prototype,使用預設值;而該預設值的 prototype 正是 Object.prototype。Object.prototype 就是原型鏈的終點,它自己的原型是 null。
這條鏈條就是屬性查找的路徑:讀取 p.someProp 時,引擎先看 p 自身,沒有就沿 __proto__ 往上找,一路到 Object.prototype 都找不到才回傳 undefined。
alert(typeof Object); // "function"
alert(typeof Function); // "function"
alert(Function.prototype); // "function() {}"
alert(Function.__proto__ == Function.prototype); // true
alert(Function.__proto__.__proto__ == Object.prototype); // true
alert(Object.__proto__ == Function.prototype); // true
alert(Object.__proto__.__proto__ == Object.prototype); // true
這幾行看起來繞口令,但結論很清楚:
因此改動 Function.prototype 會影響到 Object,改動 Object.prototype 則會影響到所有 function 的實例——這也正是為什麼「絕對不要擴充 Object.prototype」是 JS 社群的第一戒律。
今日寫 code 時,__proto__ 已不再是推薦用法(標準化的寫法是 Object.getPrototypeOf() 與 Reflect.setPrototypeOf()),而且 ES6 的 class 語法本質上就是 prototype 繼承的語法糖。理解原型鏈仍然是必要的——因為 closure、context(this 綁定)與 prototype 三者合起來,才構成 JS 有別於其他語言的完整心智模型。