JavaScript 的擴展方法與 C# 的擴充方法異曲同工:透過修改某個型別的 prototype,讓所有該型別的實例都自動擁有新的方法,還能鏈式呼叫。把常用工具集中寫成一個 js 檔全域引入,之後寫程式會順手很多。
<head>
<title>測試 JS 擴展方法</title>
<script type="text/javascript">
// 將多個連續空白合併為一個
String.prototype.ResetBlank = function() {
var regEx = /\s+/g;
return this.replace(regEx, ' ');
};
window.onload = function() {
var str = "你 在他想還好嗎?";
alert(str);
str = str.ResetBlank();
alert(str);
};
</script>
</head>
定義在 String.prototype 上的方法,所有字串都能直接呼叫,寫法跟 C# 的擴充方法幾乎一樣。
// 清除兩端的空白
String.prototype.trim = function() {
return this.replace(/(^\s*)|(\s*$)/g, '');
};
// 合併多個空白為一個
String.prototype.ResetBlank = function() {
return this.replace(/\s+/g, ' ');
};
// 只保留數字
String.prototype.GetNum = function() {
return this.replace(/[^\d]/g, '');
};
// 只保留中文
String.prototype.GetCN = function() {
return this.replace(/[^\u4e00-\u9fa5\uf900-\ufa2d]/g, '');
};
// 轉為數字,轉不了就原字串回傳
String.prototype.ToInt = function() {
return isNaN(parseInt(this)) ? this.toString() : parseInt(this);
};
// 取得位元組長度(中文算 2)
String.prototype.GetLen = function() {
var regEx = /^[\u4e00-\u9fa5\uf900-\ufa2d]+$/;
if (regEx.test(this)) {
return this.length * 2;
} else {
var oMatches = this.match(/[\x00-\xff]/g);
return this.length * 2 - oMatches.length;
}
};
// 取得檔案全名
String.prototype.GetFileName = function() {
return this.replace(/^.*([^\/?]*).*$/, '$1');
};
// 取得副檔名
String.prototype.GetExtensionName = function() {
return this.replace(/^.*\/[^\/]*(.[^.?\?]*).*$/, '$1');
};
// 取代全部
String.prototype.replaceAll = function(reallyDo, replaceWith, ignoreCase) {
if (!RegExp.prototype.isPrototypeOf(reallyDo)) {
return this.replace(new RegExp(reallyDo, (ignoreCase ? "gi" : "g")), replaceWith);
} else {
return this.replace(reallyDo, replaceWith);
}
};
// 格式化字串:String.Format("{0} 是 {1}", a, b)
String.Format = function() {
if (arguments.length === 0) return '';
if (arguments.length === 1) return arguments[0];
var reg = /{(\d+)?}/g;
var args = arguments;
return arguments[0].replace(reg, function($0, $1) {
return args[parseInt($1) + 1];
});
};
// 補零到指定位數
Number.prototype.LenWithZero = function(oCount) {
var strText = this.toString();
while (strText.length < oCount) strText = '0' + strText;
return strText;
};
// Unicode 還原為字元
Number.prototype.ChrW = function() {
return String.fromCharCode(this);
};
// 由小到大排序
Array.prototype.Min2Max = function() {
for (var i = 0; i < this.length; i++) {
for (var j = 0; j <= i; j++) {
if (this[i] < this[j]) {
var t = this[i]; this[i] = this[j]; this[j] = t;
}
}
}
return this;
};
// 取得最大值 / 最小值
Array.prototype.GetMax = function() {
var oValue = 0;
for (var i = 0; i < this.length; i++) {
if (this[i] > oValue) oValue = this[i];
}
return oValue;
};
Array.prototype.GetMin = function() {
var oValue = 0;
for (var i = 0; i < this.length; i++) {
if (this[i] < oValue) oValue = this[i];
}
return oValue;
};
// 格式化日期
Date.prototype.Format = function(format) {
var o = {
"M+": this.getMonth() + 1,
"d+": this.getDate(),
"h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12,
"H+": this.getHours(),
"m+": this.getMinutes(),
"s+": this.getSeconds(),
"q+": Math.floor((this.getMonth() + 3) / 3),
"S": this.getMilliseconds()
};
var week = { "0": "日", "1": "一", "2": "二", "3": "三", "4": "四", "5": "五", "6": "六" };
if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
}
if (/(E+)/.test(format)) {
format = format.replace(RegExp.$1,
((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "星期" : "周") : "") + week[this.getDay() + ""]);
}
for (var k in o) {
if (new RegExp("(" + k + ")").test(format)) {
format = format.replace(RegExp.$1,
(RegExp.$1.length == 1) ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
}
}
return format;
};
// 計算時間差
Date.prototype.Diff = function(interval, objDate) {
if (arguments.length < 2 || objDate.constructor != Date) return undefined;
switch (interval) {
case 's': return parseInt((objDate - this) / 1000);
case 'n': return parseInt((objDate - this) / 60000);
case 'h': return parseInt((objDate - this) / 3600000);
case 'd': return parseInt((objDate - this) / 86400000);
case 'w': return parseInt((objDate - this) / (86400000 * 7));
case 'm': return (objDate.getMonth() + 1) + ((objDate.getFullYear() - this.getFullYear()) * 12) - (this.getMonth() + 1);
case 'y': return objDate.getFullYear() - this.getFullYear();
default: return undefined;
}
};
// 使用
new Date().Format("yyyy-MM-dd hh:mm:ss E");
Object.prototype.IsNullOrEmpty = function() {
var obj = this;
if (obj == null || obj == undefined || typeof obj == 'undefined' || obj == '') return true;
if (typeof obj == 'string') {
obj = obj.trim();
if (obj == '') return true;
obj = obj.toUpperCase();
if (obj == 'NULL' || obj == 'UNDEFINED' || obj == '{}') return true;
}
return false;
};
Object.prototype 加方法最危險,會讓所有物件都多出這個屬性。上面的 IsNullOrEmpty 挂在 Object 上就是個負面示範——任何 for...in 遍歷都會被它影響,也極易與第三方套件衝突。String.prototype.trim 就是經典案例:ES5 已把它列入標準,你自行的實作反而會覆蓋掉引擎的原生(且更快)版本。Object.defineProperty 加上 enumerable: false 可以讓擴展不出現在 for...in 中,大幅降低副作用。因此現代專案更推薦不修改原型的做法:把工具函式寫成獨立函式或 lodash / date-fns 這類成熟函式庫,需要時顯式呼叫。若你確實要擴展原型,請用 Object.defineProperty、加上專屬前綴避免撞名,並把整套擴展集中在一個檔案裡清楚管理。