JavaScript: override Date.prototype.constructor
Solution 1
The reason it never gets called is because you're changing the constructor
property on Date.prototype
. However you're probably still creating a date using the code new Date()
. So it never uses your constructor. What you really want to do is create your own Date constructor:
function MyDate() {
var d = Date.apply(Date, arguments);
if ((arguments.length == 3 || arguments.length == 6)
&& (arguments[0] < 100 && arguments[0] >= 0)) {
d.setFullYear(arguments[0]);
return d;
}
Then you can create your new date like this:
var d = MyDate();
Edit: Instead of using Date.apply
I would rather use the following instantiate
function which allows you to apply arguments to a constructor function:
var bind = Function.bind;
var unbind = bind.bind(bind);
function instantiate(constructor, args) {
return new (unbind(constructor, null).apply(null, args));
}
This is how I would implement the new date constructor:
function myDate() {
var date = instantiate(Date, arguments);
var args = arguments.length;
var arg = arguments[0];
if ((args === 3 || args == 6) && arg < 100 && arg >= 0)
date.setFullYear(arg);
return date;
}
Edit: If you want to override the native Date constructor then you must do something like this:
Date = function (Date) {
MyDate.prototype = Date.prototype;
return MyDate;
function MyDate() {
var date = instantiate(Date, arguments);
var args = arguments.length;
var arg = arguments[0];
if ((args === 3 || args == 6) && arg < 100 && arg >= 0)
date.setFullYear(arg);
return date;
}
}(Date);
Solution 2
Piggybacking on Aadit M Shah's native date constructor override - this should be a reply but I don't have enough SO rep for that - as @sakthi mentioned, you'd lose your native Date methods by doing it that way. This sucks a bit because Date methods are non-enumerable, so you have to implement a bit of a hack to clone them.
First off, I'd recommend not doing it this way unless you have to. In my case, I was working in an application with a bunch of legacy code that was constructing dates using the format "m-d-yyyy", which works in chrome but not safari. I couldn't just do a find/replace in the app, because there were lots of instances where the date strings were being pulled from the service layer or the database. So, I decided to override the Date constructor in the case where there's a datestring argument in "m-d-yyyy" format. I wanted it to be as minimally-invasive as possible, so that it functions as a normal Date otherwise.
Here are my changes - it should allow you to override date with some changes to the constructor, but everything else the same. You're going to want to change the MyDate constructor before instantiate is called to do whatever you want the constructor to handle. This will happen BEFORE the system Date constructor gets applied.
var bind = Function.bind;
var unbind = bind.bind(bind);
function instantiate(constructor, args) {
return new (unbind(constructor, null).apply(null, args));
}
Date = function (Date) {
// copy date methods - this is a pain in the butt because they're mostly nonenumerable
// Get all own props, even nonenumerable ones
var names = Object.getOwnPropertyNames(Date);
// Loop through them
for (var i = 0; i < names.length; i++) {
// Skip props already in the MyDate object
if (names[i] in MyDate) continue;
// Get property description from o
var desc = Object.getOwnPropertyDescriptor(Date, names[i]);
// Use it to create property on MyDate
Object.defineProperty(MyDate, names[i], desc);
}
return MyDate;
function MyDate() {
// we only care about modifying the constructor if a datestring is passed in
if (arguments.length === 1 && typeof (arguments[0]) === 'string') {
// if you're adding other date transformations, add them here
// match dates of format m-d-yyyy and convert them to cross-browser-friendly m/d/yyyy
var mdyyyyDashRegex = /(\d{1,2})-(\d{1,2})-(\d{4})/g;
arguments[0] = arguments[0].replace(mdyyyyDashRegex, function (match, p1, p2, p3) {
return p1 + "/" + p2 + "/" + p3;
});
}
// call the original Date constructor with whatever arguments are passed in here
var date = instantiate(Date, arguments);
return date;
}
}(Date);
references:
- (this post)
- http://gpf-js.blogspot.com/2016/02/date-override.html
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties
- Copying attributes in Javascript
Solution 3
With reference to the technique mentioned in Matthew Albert's post, apart from the point which Dan Hlavenka posted, there is one more test scenario which fails. See the following code:
typeof Date() == typeof new Date() //Should be false, but it returns true
In a legacy project, there is a chance the above scenario could break few scenarios. Apart from the above and what Dan Hlavenka pointed, I agree that this is the most complete solution so far.
Lauber Bernhard
Updated on June 12, 2022Comments
-
Lauber Bernhard about 2 years
I'd like to change the behaviour of the standard Date object. Years between
0..99
passed to the constructor should be interpreted asfullYear
(no add of1900
). But my following function doesn't workvar oDateConst = Date.prototype.constructor; // save old contructor Date.prototype.constructor = function () { var d = oDateConst.apply(oDateConst, arguments); // create object with it if ( ((arguments.length == 3) || (arguments.length == 6)) && ((arguments[0] < 100) && (arguments[0] >= 0))) { d.setFullYear(arguments[0]); } return d; }
Why does it never get called? How would you solve this problem?
-
Lauber Bernhard over 11 yearsThank you What if I like to create the Date with
var d = Date()
instead of a own class? -
Aadit M Shah over 11 yearsI added an example on how to do that. See this fiddle: jsfiddle.net/ubmzs
-
Alpha almost 10 years@AaditMShah Hi! Sorry I'm two years late to the party. I have the same need, but what was so special about the
clockwork.instantiate
method? The repository seems to not exist anymore so I cannot check myself. -
Aadit M Shah almost 10 years@Alpha At the time when I wrote the answer I used to maintain the clockwork library. Now I do not maintain it anymore because I realized that it sucks. So I edited the answer and provided a definition for the
instantiate
function. -
Aadit M Shah almost 10 years@Alpha So here's the demo of the new code: jsfiddle.net/ubmzs/12. In addition I found a clone of my original repository in case you are interested: github.com/npmcomponent/aaditmshah-clockwork. Thank God that people fork code. Note to self: never delete information no matter what. What you may consider as garbage could be useful to other people. =)
-
Alpha almost 10 years@AaditMShah I really appreciate you taking the time to look those up! Thanks!
-
Admin almost 10 yearsIs there any way to override the "constructor" called to create an object literal, as in
{a: 1}
, without having to doObject({a:1})
? -
juvian over 9 years@AaditMShah I am using your code to override Date native constructor, which works great but any idea why new Date() instaceof Date gives false? A plugin I´m using stops working because of that
-
juvian over 9 years@AaditMShah Thanks a lot! Working perfectly
-
sakthi over 8 years@AaditMShah: But the overridden Date, wouldn't contain the date methods like UTC, parse, now.
-
Dan Hlavenka over 7 yearsThis is a great solution for completely replacing
Date
without impacting other code. The one thing I notice is that this will failnew Date instanceof Date
, which could cause trouble in some cases. You can fix this by addingMyDate.prototype = Date.prototype;
right beforereturn MyDate;
which according to my brief testing doesn't break any other functionality. -
Dimuth Lochana over 7 years@AaditMShah: is there any way to add UTC, parse, now functionality to this overridden Date.