prototype 是理解 JavaScript 物件模型的鑰匙。它能為內建物件或自訂類別擴充方法與屬性,也是實作繼承的基礎。以下用四個遞進的範例說明。
Number.prototype.add = function (num){
return this + num;
}
function but1_click(){
alert((3).add(8)); // 11
}
掛在 Number.prototype 上的方法,所有數字都能直接呼叫。這裡的 this 指的就是呼叫它的那個數字物件。
function Car(cColor, cWeight){
this.cColor = cColor;
this.cWeight = cWeight;
}
Car.prototype.drivers = new Array('zhangsan', 'lisi');
Car.prototype.work = function (cLong){
alert("我跑了" + cLong + "公里");
}
function but2_click(){
var c = new Car("red", "5");
c.drivers.push('zhaoliu');
alert(c.drivers);
c.work(1);
}
這裡有個容易被忽略的細節:drivers 掛在 prototype 上,代表所有 Car 實例「共用同一個陣列」。所以 c.drivers.push('zhaoliu') 之後,其他 Car 物件的 drivers 也多了一筆。若希望每個物件各自獨立,應該寫在建構子裡用 this.drivers = []。
function Rectangle(rWeight, rHeight){
this.rWeight = rWeight;
this.rHeight = rHeight;
if (typeof this._init == 'undefined'){
Rectangle.prototype.test = function (){
alert("test");
}
}
this._init = true;
}
function but3_click(){
var t = new Rectangle(6, 8);
t.test();
}
用 _init 旗標確保 prototype 上的方法只被定義一次,避免每次 new 都重新指派。
function objectA(){
this.methodA = function (){
alert("我是A方法");
}
}
function objectB(){
this.methodB = function (){
alert("我是B方法");
}
}
objectB.prototype = new objectA();
function but4_click(){
var t = new objectB();
t.methodB();
t.methodA();
}
把 B 的 prototype 指為 A 的實例,B 的物件就能沿原型鏈找到 A 的方法。這就是最基礎的原型繼承。
<body>
<h2>prototype 關鍵字的使用</h2>
<hr />
<input id="but1" type="button" value="demo1" onclick="but1_click()" />
<input id="but2" type="button" value="demo2" onclick="but2_click()" />
<input id="but3" type="button" value="demo3" onclick="but3_click()" />
<input id="but4" type="button" value="demo4" onclick="but4_click()" />
</body>
ES6 的 class 語法本質上就是 prototype 的語法糖。上面 demo4 的繼承,用 class 寫成 class B extends A {} 即可;demo1 那種擴充內建模組的做法則仍建議避免,因為一旦與其他套件的擴充撞名,會造成難以追蹤的衝突。