DIV CSS 佈局教程網

用 prototype 為內建物件擴充方法:以 Array.getMax 為例
編輯:JavaScript綜合知識     

JavaScript 的內建物件(如 Array、String、Number)都是建構函式,因此都有 prototype 屬性。往上面掛新方法,所有實例立刻就能使用,不必修改原始碼。

範例

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>prototype 屬性使用(為內建物件添加新的方法)</title>
<script type="text/javascript">
function getMaxFunc() {
  var max = this[0];
  for (var i in this) {
    if (max < this[i]) {
      max = this[i];
    }
  }
  return max;
}

// Array 是 JavaScript 的內建物件,
// 這裡用 prototype 定義一個名為 getMax 的新方法
Array.prototype.getMax = getMaxFunc;

var myArr = [3, 5, 6, 7, 9];
// 之後就能像使用內建方法一樣呼叫
var max = myArr.getMax();
alert("max=" + max);
</script>
</head>
<body></body>
</html>

運作原理

呼叫 myArr.getMax() 時,JavaScript 先在 myArr 自身找不到 getMax,於是沿著原型鏈往上找到 Array.prototype,找到後以 myArr 作為 this 呼叫它。因此函式中的 this 就是陣列本身,this[0] 是第一個元素。

這個寫法的兩個問題

第一,for...in 會走訪原型鏈上所有可列舉屬性。一旦有人擴充了 Array.prototype,這個迴圈就會把方法名稱也當成索引來讀取,導致 this[i] 拿到函式物件而比較出錯。改用傳統 for 迴圈更穩妥:

Array.prototype.getMax = function () {
  var max = this[0];
  for (var i = 1; i < this.length; i++) {
    if (this[i] > max) { max = this[i]; }
  }
  return max;
};

第二,也是更重要的一點:修改內建物件原型被普遍視為不良實務。若兩個函式庫各自擴充了同名方法但行為不同,就會產生難以追蹤的衝突;而 for...in 造成的連帶影響,在早期也曾引發大量問題。

推薦的替代方案

// 1. 直接用現成的內建方法
Math.max.apply(null, [3, 5, 6, 7, 9]);   // 9
Math.max(...[3, 5, 6, 7, 9]);            // 9(ES2015 展開語法)

// 2. 用 reduce 自行歸納
[3, 5, 6, 7, 9].reduce(function (a, b) { return b > a ? b : a; });

// 3. 封裝成獨立工具函式
function getMax(arr) {
  return arr.reduce((a, b) => Math.max(a, b), -Infinity);
}

原型擴充的正當用途,主要是 polyfill——也就是為舊環境補上標準但未實作的方法(如 Array.prototype.includes),且實作前會先檢查該方法是否已存在。這種情況與「為了方便而任意加新方法」有本質上的差別。

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