每個建構函式都有 prototype 屬性,指向一個共享物件。透過修改 Prototype 可為**所有實例**新增方法/屬性,實現「開放擴充、封閉修改」。
// 數字相加
Number.prototype.add = function(num) { return this + num; };
alert((3).add(15)); // 18
// 布林取反
Boolean.prototype.rev = function() { return !this; };
alert((true).rev()); // false
// 原生 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.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)
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空"
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")); // 月數差
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 迴圈。if (!Array.prototype.pushPro) ...。