JavaScript 的原型繼承機制允許我們為內建物件 (Array、String、Date 等) 新增方法,讓所有實例共享。本文以「為 Array 新增 `getMax()` 取得最大值」為例,完整示範原型擴展流程、最佳實踐、潛在風險與現代替代方案。
// 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
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` 擴充介面定義 | 🟡 低 |
設定 `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
// 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
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}
// 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"