萬盛學電腦網

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

JavaScript Prototype 原型擴展內建物件:為 Array 新增 getMax 方法完整教學

JavaScript 的原型繼承機制允許我們為內建物件 (Array、String、Date 等) 新增方法,讓所有實例共享。本文以「為 Array 新增 `getMax()` 取得最大值」為例,完整示範原型擴展流程、最佳實踐、潛在風險與現代替代方案。

基本實作:擴展 Array.prototype

// 1. 定義邏輯函式
function getMaxFunc() {
    var max = this[0];
    for (var i in this) {
        // 注意:for...in 會遍歷繼承屬性,建議用 for 迴圈或 Object.keys
        if (this.hasOwnProperty(i) && max < this[i]) {
            max = this[i];
        }
    }
    return max;
}

// 2. 掛載到 Array.prototype
Array.prototype.getMax = getMaxFunc;

// 3. 所有陣列實例自動擁有此方法
var myArr = [3, 5, 6, 7, 9];
var max = myArr.getMax(); // 像內建方法一樣呼叫
console.log("max =", max); // 9

改良版:更健壯的 getMax

Array.prototype.getMax = function() {
    // 防禦性程式設計
    if (this.length === 0) return undefined;
    
    // 使用標準迴圈避免 for...in 遍歷繼承屬性
    var max = this[0];
    for (var i = 1; i < this.length; i++) {
        if (this[i] > max) max = this[i];
    }
    return max;
};

// 更進階:支援比較函式
Array.prototype.maxBy = function(comparer) {
    if (this.length === 0) return undefined;
    var max = this[0];
    for (var i = 1; i < this.length; i++) {
        if (comparer(this[i], max) > 0) max = this[i];
    }
    return max;
};

// 使用
var users = [
    {name: 'A', age: 20},
    {name: 'B', age: 30},
    {name: 'C', age: 25}
];
var oldest = users.maxBy((a, b) => a.age - b.age);
console.log(oldest); // {name: 'B', age: 30}

原型擴展的風險與爭議

風險說明嚴重度
命名衝突未來標準新增同名方法 (如 `Array.prototype.flat`)、或其他庫也擴展同名方法,導致覆蓋/行為不一致🔴 高
for...in 污染擴展的方法會出現在 `for...in` 迴圈中,破壞遍歷邏輯🟠 中
不可配置/不可枚舉預設 `enumerable: true`,無法像內建方法那樣隱藏🟡 低
跨框架污染微前端、iframe 嵌入時原型污染跨越邊界🔴 高
TypeScript 型別缺失需額外撰寫 `.d.ts` 擴充介面定義🟡 低

安全擴展模式:Object.defineProperty

設定 `enumerable: false` 隱藏 `for...in` 遍歷,模擬內建方法行為:

Object.defineProperty(Array.prototype, 'getMax', {
    value: function() {
        if (this.length === 0) return undefined;
        var max = this[0];
        for (var i = 1; i < this.length; i++) {
            if (this[i] > max) max = this[i];
        }
        return max;
    },
    writable: true,
    configurable: true,
    enumerable: false // 關鍵:不出現在 for...in / Object.keys
});

// 驗證
var arr = [1,2,3];
console.log(arr.getMax()); // 3
console.log(Object.keys(arr)); // ["0","1","2"] - 不含 getMax
for (var k in arr) console.log(k); // "0","1","2" - 不含 getMax

現代最佳替代方案

1. 獨立工具函式 (Tree-shaking 友善)

// utils/array.js
export function getMax(arr) {
    if (!arr?.length) return undefined;
    return Math.max(...arr); // 現代寫法,極簡高效
}

export function maxBy(arr, selector) {
    if (!arr?.length) return undefined;
    return arr.reduce((max, cur) => selector(cur) > selector(max) ? cur : max);
}

// 使用
import { getMax, maxBy } from './utils/array';
getMax([3,5,6,7,9]); // 9

2. 現代原生 API (無需擴展)

const arr = [3, 5, 6, 7, 9];

// 最大值
Math.max(...arr); // 9
// 或
arr.reduce((a, b) => Math.max(a, b)); // 9

// 最小值
Math.min(...arr); // 3

// 依條件最大
const users = [{age:20}, {age:30}, {age:25}];
users.reduce((max, u) => u.age > max.age ? u : max); // {age:30}

3. TypeScript 擴充介面 (若堅持擴展)

// global.d.ts
interface Array {
    getMax(this: T[]): T | undefined;
    maxBy(this: T[], comparer: (a: T, b: T) => number): T | undefined;
}

// 實作檔
Array.prototype.getMax = function() { /* ... */ };
Array.prototype.maxBy = function(comparer) { /* ... */ };

其他常見內建物件擴展範例

// String: 首字大寫
Object.defineProperty(String.prototype, 'capitalize', {
    value: function() { return this.charAt(0).toUpperCase() + this.slice(1); },
    enumerable: false
});
"hello".capitalize(); // "Hello"

// Date: 格式化
Object.defineProperty(Date.prototype, 'format', {
    value: function(fmt = 'YYYY-MM-DD') {
        const o = {
            'Y+': this.getFullYear(),
            'M+': this.getMonth() + 1,
            'D+': this.getDate(),
            'h+': this.getHours(),
            'm+': this.getMinutes(),
            's+': this.getSeconds()
        };
        return fmt.replace(/([YMDhms]+)/g, (m, k) => {
            const v = o[k];
            return v !== undefined ? String(v).padStart(m.length, '0') : m;
        });
    },
    enumerable: false
});
new Date().format('YYYY-MM-DD hh:mm:ss'); // "2025-01-13 14:30:05"

// Number: 千分位
Object.defineProperty(Number.prototype, 'toLocale', {
    value: function() { return this.toLocaleString(); },
    enumerable: false
});
(1234567).toLocale(); // "1,234,567"

總結建議

  1. 應用層代碼:**嚴禁擴展內建原型**,使用獨立工具函式或現代原生 API
  2. 庫/框架作者:若必須擴展,用 `Object.defineProperty` 設 `enumerable: false`,並完善 TypeScript 類型定義
  3. Polyfill 場景:為舊瀏覽器補齊標準方法 (如 `Array.prototype.includes`),可擴展但需符合規格
  4. 程式碼審查:任何 `Array.prototype.xxx = ...` 都應被攔截討論
copyright © 萬盛學電腦網 all rights reserved