我打算命名我的有用方法库,但我的库也包含了许多原型。例如,
// Utility Functions - Trim() removes trailing, leading, and extra spaces between words
String.prototype.Trim = function () { var s = this.replace(/^\s+/,"").replace(/\s+$/,""); return s.replace(/\s+/g," "); };
// Escapes characters for use with a regular expression
String.prototype.EscapeR = function () { return this.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); };
Date.prototype.getMonthName = function() {
if ( !this.mthName ) this.mthName = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
return this.mthName[this.getMonth()];
};
我如何(或应该)将它们包含在我的命名空间中?
(请注意,我没有使用JQuery。)感谢您提前提示。安迪。
答案 0 :(得分:2)
最简单的解决方案是使用自定义命名空间前缀。但是,你可以使用Mozilla的非标准__noSuchMethod__
做一些偷偷摸摸的事情:使用monkey.js,你可以做到
var names = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',
'Sep', 'Oct', 'Nov', 'Dec' ];
MONKEY.patch(Date).getMonthName = function() {
return names[this.getMonth()];
};
var date = MONKEY(new Date);
alert(date.getMonthName());
符合标准的版本可以在ECMAScript-Harmony proxies登陆后完成......
答案 1 :(得分:0)
您可以将它们封装在通常命名的子对象中,例如:
String.prototype.stuff = {
Trim: function() { ... }
}
Date.prototype.stuff = {
getMonthName: function() { ... }
}
当然,这只会使你的方法相对于它们的容器对象保持名称空间,但我认为这就是你要拍摄的内容。