Let me start with a concrete example of what I'm trying to do.
I have an array of components of the year, month, day, hour, minute, second and millisecond in the form [ 2008, 10, 8, 00, 16, 34, 254 ] . I would like to instantiate a Date object using the following standard constructor:
new Date(year, month, date [, hour, minute, second, millisecond ])
How to pass an array to this constructor to get a new Date instance? [ Update . My question really goes beyond this specific example. I would like to get a general solution for inline JavaScript classes such as Date, Array, RegExp, etc., whose constructors are not available. ]
I am trying to do something like the following:
var comps = [ 2008, 10, 8, 00, 16, 34, 254 ]; var d = Date.prototype.constructor.apply(this, comps);
I probably need " new ". The above just returns the current time, as if I called " (new Date()).toString() ". I also admit that I can be completely in the wrong direction with the above :)
Note : There is no eval() and without access to the elements of the array one by one, please. I am sure that I should use the array as is.
Update: further experiments
Since no one could find a working answer, I played more. Here is a new discovery.
I can do this with my own class:
function Foo(a, b) { this.a = a; this.b = b; this.toString = function () { return this.a + this.b; }; } var foo = new Foo(1, 2); Foo.prototype.constructor.apply(foo, [4, 8]); document.write(foo);
But it does not work with the inner class Date:
var d = new Date(); Date.prototype.constructor.call(d, 1000); document.write(d);
It also does not work with Number:
var n = new Number(42); Number.prototype.constructor.call(n, 666); document.write(n);
Maybe this is simply not possible with internal objects? I am testing using Firefox BTW.