DIV CSS 佈局教程網

JavaScript prototype 的功能與使用範例
編輯:JavaScript綜合知識     

prototype 是理解 JavaScript 物件模型的鑰匙。它能為內建物件或自訂類別擴充方法與屬性,也是實作繼承的基礎。以下用四個遞進的範例說明。

demo1:為內建物件擴充方法

Number.prototype.add = function (num){
  return this + num;
}

function but1_click(){
  alert((3).add(8));   // 11
}

掛在 Number.prototype 上的方法,所有數字都能直接呼叫。這裡的 this 指的就是呼叫它的那個數字物件。

demo2:為自訂類別加上屬性與方法

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 = []。

demo3:較緊湊的寫法

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 都重新指派。

demo4:以 prototype 實作繼承

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 那種擴充內建模組的做法則仍建議避免,因為一旦與其他套件的擴充撞名,會造成難以追蹤的衝突。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved