Andy G
Andy G

Reputation: 19367

How can I 'namespace' my prototypes

I intend to namespace my library of useful methods but my library also includes a number of prototypes. For example,

// 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()];
};

How can I (or should I) include them within my namespace?

(Please note that I am not using JQuery.) Thanks for any hints in advance. Andy.

Upvotes: 0

Views: 352

Answers (2)

Christoph
Christoph

Reputation: 169573

The easiest solution would be to just use a custom namespace prefix. However, you can do some sneaky things using Mozilla's non-standard __noSuchMethod__: Using monkey.js, you could do

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

A standard-compliant version can be done once ECMAScript-Harmony proxies have landed...

Upvotes: 2

dml
dml

Reputation: 469

You can encapsulate them in a commonly-named sub object, like:

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

Of course, this only keep your methods namespaced relative to their container object but I assume that's what you're shooting for.

Upvotes: 0

Related Questions