萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript Prototype 擴充內建類型完整實戰指南

什麼是 Prototype?

每個建構函式都有 prototype 屬性,指向一個共享物件。透過修改 Prototype 可為**所有實例**新增方法/屬性,實現「開放擴充、封閉修改」。

基礎範例:為 Number、Boolean 新增方法

// 數字相加
Number.prototype.add = function(num) { return this + num; };
alert((3).add(15)); // 18

// 布林取反
Boolean.prototype.rev = function() { return !this; };
alert((true).rev()); // false

增強現有方法:Array.push 多參數版

// 原生 push 僅支援單一參數(ES5 已支援多參數,此為教學示範)
Array.prototype.pushPro = function() {
  var len = this.length;
  for (var i = 0; i < arguments.length; i++) {
    this[len + i] = arguments[i];
  }
  return this.length;
};
var arr = [1,2];
arr.pushPro(3,4,5); // arr = [1,2,3,4,5]

修正 String.length 全半形長度差異

String.prototype.cnLength = function() {
  var matches = this.match(/[^\x00-\xff]/g); // 非 ASCII 字元(全形)
  return this.length + (matches ? matches.length : 0);
};
alert("EaseWe空間Spaces".cnLength()); // 16(英文 10 + 中文 3×2)

實戰新功能

1. String.left(n, strict) — 取左側 n 字元,支援全半形

String.prototype.left = function(num, strict) {
  if (!/\d+/.test(num)) return this;
  var str = this.substr(0, num);
  if (!strict) return str;
  // strict 模式:按視覺寬度截取
  var fullWidthCount = str.cnLength() - str.length;
  num = num - Math.floor(fullWidthCount / 2);
  return this.substr(0, num);
};
alert("EaseWe空間Spaces".left(8));        // "EaseWe空間"
alert("EaseWe空間Spaces".left(8, true));  // "EaseWe空"

2. Date.DayDiff(otherDate, unit) — 計算兩日期差距

Date.prototype.DayDiff = function(other, unit) {
  if (!(other instanceof Date)) return 0;
  var msPerDay = 86400000;
  var diff = Math.abs(this - other);
  switch (unit) {
    case "y": diff /= msPerDay * 365; break;
    case "m": diff /= msPerDay * 365 / 12; break;
    case "w": diff /= msPerDay * 7; break;
    default:  diff /= msPerDay; // day
  }
  return Math.floor(diff);
};
alert((new Date()).DayDiff(new Date(2002,0,1)));       // 天數差
alert((new Date()).DayDiff(new Date(2002,0,1), "m"));  // 月數差

3. Number.fact() — 階乘(遞歸示範)

Number.prototype.fact = function() {
  var n = Math.floor(this);
  if (n < 0) return NaN;
  if (n <= 1) return 1;
  return n * (n-1).fact();
};
alert((4).fact()); // 24

注意事項

  • **不要**在 Object.prototype 上擴充,會污染所有物件的 for...in 迴圈。
  • 現代開發建議使用 **獨立工具函式** 或 **ES6 Class 繼承** 替代直接修改內建 Prototype,避免衝突與副作用。
  • 若必須修補(Polyfill),請先檢查 if (!Array.prototype.pushPro) ...。
copyright © 萬盛學電腦網 all rights reserved