prototype 是 JavaScript 物件導向的核心機制,也是面試與閱讀原始碼時的必經關卡。本文從定義出發,一路談到實際擴充內建型別。
JavaScript 中物件的 prototype 屬性,用來回傳該物件類型的原型參照。我們透過 prototype 為物件的一類提供一組基本功能,而該物件的新實例會「繼承」賦予在原型上的操作。
JavaScript 手冊的說法是:所有 JavaScript 內部物件都有唯讀的 prototype 屬性,可以向其原型中動態添加功能(屬性和方法),但該物件不能被賦予不同的原型;然而使用者自訂的物件則可以被賦予新的原型。
在 JavaScript 中,prototype 物件是實現物件導向的重要機制。每個函式就是一個物件(Function),函式物件都有一個子物件 prototype。類別是以函式的形式來定義的,prototype 表示該函式的原型,也代表一個類別的成員集合。當透過 new 建立一個類別的實例時,prototype 物件的成員都會成為實例化物件的成員。
整理成兩條要點:
new 實例化之後,其成員才會被實例化,實例物件方可呼叫。同時要注意,函式本身也是物件,若直接在函式上宣告成員,不必實例化即可呼叫。
JavaScript 並非透過類別繼承(如 Java)來支援繼承,而是使用一種鏈接機制。每個 JavaScript 物件都有一個內建屬性名為 prototype,它保存著對另一個物件的參照,該物件作為當前物件的「父物件」。
當用點記法參照物件的函式或屬性時,若該物件上沒有這個成員,就會轉而檢查它的 prototype 所參照的物件,看是否有請求的屬性或函式。若那個物件也沒有,就再檢查它的 prototype,如此沿著鏈向上查找,直到找到為止,或抵達鏈尾此時回傳 undefined。
從這個意義上說,這種繼承結構其實更接近「has a」關係,而非「is a」關係——這是 prototype 與傳統類別繼承最根本的哲學差異。
function func() {
func.prototype.name = "prototype of func";
}
var f = new func();
alert(f.name); // prototype of func
先建立 func 物件,在它的 prototype 上設定 name 屬性,實例化 f 之後,f 就能透過原型鏈讀到這個屬性。
常見的內建類別包括 Array、Boolean、Date、Function、Number、Object、String 等。它們既有的方法(如陣列的 push、日期的 get 系列、字串的 split)雖然常用,但實際開發時難免會遇到不足,這正是 prototype 派上用場的地方。
(1)數字相加
Number.prototype.add = function(num) {
return (this + num); // 這裡的 this 指向 Number
};
alert((3).add(15)); // 18
(2)布林取反
Boolean.prototype.rev = function() { return (!this); };
alert((true).rev()); // false
(3)增強 Array.push:一次加入多個元素
Array.prototype.push = function(new_element) {
this[this.length] = new_element;
return this.length;
};
Array.prototype.pushPro = function() {
var currentLength = this.length;
for (var i = 0; i < arguments.length; i++) {
this[currentLength + i] = arguments[i];
}
return this.length;
}
用 arguments 接住任意個參數,就能突破原生 push 的限制。以此類推,你也可以增強 Array.pop 來實作「刪除任意位置、任意多個元素」。
(4)String.left():區分全形半形的左截取
用過 VB 的都知道 left 函式,從字串左邊取 n 個字元。但它的問題是把全形、半形都視為一個字元,在中英文混排的版面中無法截取等長的字串。
String.prototype.left = function(num, mode) {
if (!/\d+/.test(num)) return (this);
var str = this.substr(0, num);
if (!mode) return str;
var n = str.Tlength() - str.length; // 全形字元造成的長度差
num = num - parseInt(n / 2);
return this.substr(0, num);
};
alert("aa啦啦aa".left(4)); // aa啦啦
alert("aa啦啦aa".left(4, true)); // aa啦
這裡用到了另一個自訂方法 String.Tlength() 來計算顯示寬度,說明了自訂方法之間也能互相組合,長出更實用的新方法。
(5)Date.DayDiff():計算兩個日期的間隔
Date.prototype.DayDiff = function(cDate, mode) {
try { cDate.getYear(); }
catch (e) { return (0); } // 參數不是日期就回傳 0
var base = 60 * 60 * 24 * 1000;
var result = Math.abs(this - cDate);
switch (mode) {
case "y": result /= base * 365; break;
case "m": result /= base * 365 / 12; break;
case "w": result /= base * 7; break;
default: result /= base; break;
}
return (Math.floor(result));
};
alert((new Date()).DayDiff(new Date(2002, 0, 1))); // 天數
alert((new Date()).DayDiff(new Date(2002, 0, 1), "m")); // 月數
用 try...catch 來確認參數是否為日期物件,是個便宜但有效的防呆手法。若要更嚴謹,改用 cDate instanceof Date 會更直接。
(6)Number.fact():遞迴也可以寫在 prototype 裡
Number.prototype.fact = function() {
var num = Math.floor(this);
if (num < 0) return NaN;
if (num == 0 || num == 1) return 1;
else return (num * (num - 1).fact());
};
alert((4).fact()); // 24
注意 (num - 1).fact() 這個寫法:因為 fact 掛在 Number 的原型上,任何數字都能直接呼叫它,遞迴於焉成立。
(7)Array.MAX():取最大值
var oArr = [100, 190, 199, 189, 3000, 400, 4001];
Array.prototype.MAX = function() {
var i, max = this[0];
for (i = 1; i < this.length; i++) {
if (max < this[i]) { max = this[i]; }
}
return max;
};
alert(oArr.MAX()); // 4001
function TestObject() {
this.m_Name = "ffffffffff";
}
TestObject.prototype.ShowName = function() {
alert(this.m_Name);
};
var f = new TestObject();
f.ShowName();
function TestObjectA() {
this.MethodA = function() { alert('TestObjectA.MethodA()'); };
}
function TestObjectB() {
this.MethodB = function() { alert('TestObjectB.MethodB()'); };
}
TestObjectB.prototype = new TestObjectA();
把 B 的原型設為 A 的實例,B 的實例就能透過原型鏈使用 A 的方法。這是最直白的原型繼承寫法,但它有個眾所皆知的缺點:A 的實例只有一個,被所有 B 的實例共享,因此若 A 的建構過程中有需要各自獨立的狀態,就會出問題。後來的「寄生組合式繼承」正是為了解決這一點而生。
function RP() {
RP.PropertyA = 1;
RP.MethodA = function() { alert("RP.MethodA "); };
this.PropertyA = 100;
this.MethodA = function() { alert("this.MethodA"); };
}
RP.prototype.PropertyA = 10;
RP.prototype.MethodA = function() { alert("RP.prototype.MethodA"); };
rp = new RP();
alert(RP.PropertyA); // 1 函式自身的靜態屬性
RP.MethodA(); // RP.MethodA
alert(rp.PropertyA); // 100 實例屬性優先
rp.MethodA(); // this.MethodA
delete RP.PropertyA;
alert(RP.PropertyA); // undefined
delete rp.PropertyA;
alert(rp.PropertyA); // 100 ← 刪不掉?
delete rp.MethodA;
rp.MethodA(); // RP.prototype.MethodA 原型屬性接手
這個例子把查找優先順序演示得很清楚:實例屬性 > 原型屬性 > undefined;而掛在函式物件上的屬性(靜態屬性)屬於完全不同的層次,只有透過 RP.PropertyA 存取得到,實例拿不到。
最後兩行的對比特別有意思:刪掉實例屬性之後,存取會回落到原型上,於是 rp.MethodA() 呼叫到的是 RP.prototype.MethodA。這就是原型鏈最直接的證明。
<script type="text/javascript">
function Circle(x, y, r) {
this.x = x;
this.y = y;
this.r = r;
// this.prototype = null;
/* 這行程式碼可視為隱含存在的。因為 JavaScript 中「類別」的定義
與函式的定義在結構上沒有差異,所以可以說所有函式都隱藏有
這樣一個屬性。 */
}
Circle.prototype.area = function() {
return this.r * this.r * 3.1415926;
};
var Circ = new Circle(0, 0, 5);
alert(parseInt(Circ.area())); // 78
</script>
把 area 放在 prototype 而非建構函式內部,是關鍵的效能考量:this.area = function(){} 每建立一個實例就會複製一份函式,而 Circle.prototype.area 只存在一份、被所有實例共享。實例數量多時,這個差異相當可觀。
擴充內建物件的原型(尤其是 Object.prototype)在大型專案中極易與第三方函式庫衝突,主流觀點普遍不建議這麼做。較穩妥的做法是建立自己的工具物件或 namespace,把擴充方法掛在那上面。ES6 的 class 語法本質上仍是 prototype 的語法糖,理解本文的機制之後,再去看 class 的 extends 與 super 會通透許多。