Overriding the Javascript Date constructor?
I also faced this problem and ended up writing a module for that. Perhaps it's useful for somebody:
Github: https://github.com/schickling/timemachine
timemachine.config({
dateString: 'December 25, 1991 13:12:59'
});
console.log(new Date()); // December 25, 1991 13:12:59
I tested your code:
// create a date object for this Friday:
var d = new Date(2012, 0, 20);
//override Date constructor so all newly constructed dates return this Friday
Date = function(){return d;};
var now = new Date()
console.log(now);
now = new Date()
console.log(now);
now = new Date()
console.log(now);
now = new Date()
console.log(now);
And the result ???? Why so different?
Date {Fri Jan 20 2012 00:00:00 GMT+0700 (SE Asia Standard Time)}
Date {Fri Jan 20 2012 00:00:00 GMT+0700 (SE Asia Standard Time)}
Date {Fri Jan 20 2012 00:00:00 GMT+0700 (SE Asia Standard Time)}
Date {Fri Jan 20 2012 00:00:00 GMT+0700 (SE Asia Standard Time)}
EDIT:
I saw that whenever you interact with the Date Picker, the behavior goes different. Try another test, change the now
is something like interact with Date Picker:
// create a date object for this Friday:
var d = new Date(2012, 0, 20);
//override Date constructor so all newly constructed dates return this Friday
Date = function(){return d;};
var now = new Date();
var another = new Date();
console.log(now);
another.setDate(13);
now = new Date()
console.log(now);
And the result is:
Date {Fri Jan 20 2012 00:00:00 GMT+0700 (SE Asia Standard Time)}
Date {Fri Jan 13 2012 00:00:00 GMT+0700 (SE Asia Standard Time)}
So, what goes wrong? You already overridden core Date function by
Date = function(){return d;}; // after construction, all date will be d (2012-01-20)
var now = new Date(); // you instantiate a date, but actually now variable is d (2012-01-20)
var another = new Date(); // you instantiate a date, but another is still d (2012-01-20)
another.setDate(13); // change another date to 13 is to change now to 13 (because now and another is still one d)
now = new Date() // still d
console.log(now); // print out now (2012-01-13)
So, you overrides core Date function by a function that causes all date use the same (just one) instance, which is d (2012-01-20). Change any dates affect others.