views:

141

answers:

2

I'm replacing (overriding, improving, adding functionality to) a method in the prototype of the Date object. Here is a simplified version of what I've done:

Date.prototype._toString = Date.prototype.toString;

Date.prototype.toString = function(mask) {
    if(mask == undefined){return this._toString();}
    //snip
    //...
    //snip
    return date_string;
}

As I don't want to lose the standard method, I'm assigning the original method to a temporal variable and calling it if appropriate.

Is there a way of doing this without polluting the Date.prototype namespace?

What I'm asking is this same question, only in Javascript.

+7  A: 

You can do it like this:-

(function() {
    var _toString = Date.prototype.toString;
    Date.prototype.toString = function(mask) {
       if (mask == undefined) { return _toString.call(this); }
    //snip
    }
 })();
AnthonyWJones
+1  A: 

While the above solution is more elegant is the way that it doesn't pollute the Date.prototype, calls to the "new" toString will be slowed down because of the closure it involves.

It terms of speed, you'll be better off the way you mentioned in your question. Try a loop that calls your code 20,000 times and then try the code submitted by Anthony.

Depending on how often your code is called, you'll want to go one way or the other.

Cheers!

Update: you can read this little sample from Google

Oli