Javascript 我怎么能';名称空间';我的原型

Javascript 我怎么能';名称空间';我的原型,javascript,namespaces,Javascript,Namespaces,我打算命名我的有用方法库,但我的库还包括许多原型。比如说, // 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," "); }; // Esc

我打算命名我的有用方法库,但我的库还包括许多原型。比如说,

// 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。)感谢您提前提供任何提示。Andy。

您可以将它们封装在一个通用命名的子对象中,如:

String.prototype.stuff = {
  Trim: function() { ... }
}
Date.prototype.stuff = {
  getMonthName: function() { ... }
}

当然,这只会使您的方法相对于其容器对象保持名称空间,但我认为这就是您的目标。

最简单的解决方案是只使用自定义名称空间前缀。但是,您可以使用Mozilla的非标准
\uuuuuNosuchMethod\uuuuuuuu
做一些鬼鬼祟祟的事情:使用

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());

标准兼容版本可以在登陆后完成…

Huh这是一种不添加全局功能(可能干扰现有功能)的聪明方法。我应该看看这个猴子。如果独立脚本使用,
monkey()
的当前实现仍然存在相同的问题(即命名冲突);然而,一旦您有了代理,添加一些名称空间功能应该不会太难;我会看一看,我还有更多的时间…谢谢你的回复,尽管也许我应该提到我对名称空间有点陌生。我喜欢MONKEY解决方案,但假设这是另一个库?我不能有自己的“补丁”方法吗?“不会工作,因为这将指向错误的对象”-不确定这是指哪个答案?我已经开始给我的小库命名了,但是我在函数中提到了“this”,我相信它仍然是指我的类,而不是它所在的函数对象。“this”中的“this”是指“this current object”,我怎么能告诉它呢。有什么意义吗?