I'm trying to monkey patch a javascript Date constructor.
I have the following code:
var __Date = window.Date;
window.Date = function(){
__Date.apply(this, Array.prototype.slice.call(arguments));
};
window.Date.prototype = __Date.prototype;
As far as I know the javascript constructor (when called) does three things:
- It creates a new object that the
thispoints to when the constructor function is executed - It sets up this object to delegate to this constructor's prototype.
- It executes the constructor function in the context of this newly created object.
Ad.1 is accomplished automatically by the way that the new Date function will be called (new Date())
Ad.2 if accomplished by setting my new Date.prototype to be the original Date.prototype.
Ad.3 is accomplished by calling the original Date function in the context of the newly created object with the same paramters that are passed to "my" Date function.
Somehow it does not work. When i call e.g. new Date().getTime() i get an error saying that TypeError: this is not a Date object.
Why doesn't it work? Even this code:
new Date() instanceof __Date
returns true so by setting the same prototypes i fooled the instanceof operator.
PS. the whole point of this is that I want to check the arguments passed to the Date constructor and alter them when a certain condition is met.