1

Given this code:

function Test(){
    var $D = Date.prototype;
    $D.addDays=function(value){this.setDate(this.getDate()+value);return this;};
    $D.clone = function() {
        return new Date(this.getTime());
    };
    alert(new Date().addDays(5));
    var x = 5;
}

Test();

alert(new Date().addDays(1));
​alert(x);​

The only error is thrown by alert(x) which throws the "x is undefined" error, because x is limited to function Test()

The call to addDays() works both within the function and outside it.

I'm assuming this is because the scope of the Date prototype is global, so it's irrelevant that I extend it within a closure.

So if I wanted to extend Date within a closure, BUT NOT allow any other javascript to get the extension, how would I do it?

The reason I'm asking is because when I'm extending core javascript objects, I don't want to conflict with other libraries which may make the same modifications.

4

1 回答 1

1

There are a couple ways to do what you're talking about. You can just delete your changes when you're done:

function Test() {
    var $D = Date.prototype;
    // ...
    delete $D.addDays;
    delete $D.clone;
}

This would work if you needed the methods only during a single execution. It wouldn't work if you need the methods to be available indefinitely, but only within your module.

If that's not the case, you can add the extension methods directly to the Date objects you (not to the prototype). Within your module, you could have a function that creates these special Date objects for you:

function createDate() {
    var d = new Date();
    d.method1 = function() { ... };
    d.method2 = function() { ... };
    return d;
}

Finally, you can use helper functions scoped within your closure instead of extending the prototype. Really, extending the prototype is just syntactic sugar for you in this case anyway.

于 2012-07-17T17:51:17.493 回答