Rationale behind supporting "Invalid Date"
Brendan Eich
brendan at mozilla.com
Sat Feb 11 17:32:53 PST 2012
It's well-specified by 15.9.3.1 etc.
This is all based on java.util.Date from ages ago, sorry it is painful.
Have you considered wrapping Date with a user-defined function that
throws if an invalid Date with a NaN time-value is created? Something
like this:
var Date = function (origDate) {
"use strict";
return function Date() {
if (!(this instanceof Date)) {
// Approximate test for called-as-function, use apply.
return origDate.apply(this, arguments);
}
var args = [].slice.apply(arguments);
args.unshift(this);
var ctor = origDate.bind.apply(origDate, args);
var date = new ctor;
var time = date.getTime();
if (time !== time) {
throw 'Invalid Date';
}
return date;
};
}(this.Date);
/be
Andrew Paprocki wrote:
> I'm wondering if someone can point me to any past rationale for the
> decision to support Date objects in an "Invalid Date" state instead of
> throwing an exception whenever the user attempts to form an invalid
> date?
>
> Tracking down the source of script errors is difficult if something
> like "new Date(undefined)" is done, followed by a ".getTime()",
> propagating a NaN down layers of abstraction. Additional strange cases
> involve using NaN, Infinity, etc throughout the Date API.
>
> I was curious if there is a good reason for this or if potentially
> undefined / non-finite numbers could throw in a strict-mode setting. I
> didn't notice this behavior in the spec, but all browsers appear to
> follow the same convention.
>
> -Andrew
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
More information about the es-discuss
mailing list