Here's how you do it:
function applyToConstructor(constructor, argArray) { var args = [null].concat(argArray); var factoryFunction = constructor.bind.apply(constructor, args); return new factoryFunction(); } var d = applyToConstructor(Date, [2008, 10, 8, 00, 16, 34, 254]);
The call is a little easier
function callConstructor(constructor) { var factoryFunction = constructor.bind.apply(constructor, arguments); return new factoryFunction(); } var d = callConstructor(Date, 2008, 10, 8, 00, 16, 34, 254);
You can use any of these to create factory functions:
var dateFactory = applyToConstructor.bind(null, Date) var d = dateFactory([2008, 10, 8, 00, 16, 34, 254]);
or
var dateFactory = callConstructor.bind(null, Date) var d = dateFactory(2008, 10, 8, 00, 16, 34, 254);
It will work with any constructor, not just built-in or constructors that can work as functions (e.g. Date).
However, this requires a function. Gaskets are likely to work incorrectly.
Another approach, more similar to the style of some other answers, is to create a functional version of the inline new . This will not work on all embedded devices (e.g. Date).
function neu(constructor) {
And now, of course, you can do .apply or .call or .bind on neu as usual.
For example:
var personFactory = neu.bind(null, Person); var d = personFactory("Harry", "Potter");
I feel that the first solution I give is better, though, since it does not depend on you, correctly replicating the semantics of the built-in and working correctly with the built-in ones.