Javascript - Create instance with array of arguments

@Raynos answer works well, except that the non-ES5 version is missing the constructor's prototype after instantiation.

Here's my updated cApply method:

var cApply = function(c) {
  var ctor = function(args) {
    c.apply(this, args);
  };
  ctor.prototype = c.prototype;
  return ctor;
};

Which can be used like this:

var WrappedConstructor = cApply(Constructor);
var obj = new WrappedConstructor([1,2,3]);

// or inline like this.    
var obj2 = new (cApply(Constructor))([1,2,3]);

JSFiddle for reference.


with ECMAscript 5 you can:

function createInstanceWithArguments (fConstructor, aArgs) {
    var foo = Object.create(fConstructor.prototype);
    fConstructor.apply(foo, aArgs);
    return foo;
}

You can curry the functions:

function A(arg1, arg2) {
    // ...
}

function A12() {
    A(1, 2);
}

You could even build a curry factory:

function A_curry() {
    var args = arguments;
    return function () {
        A.apply(null, args);
    };
}

var wrapper = function(f, args) {
    return function() {
        f.apply(this, args);
    };
};

function Constructor() {
    this.foo = 4;
}
var o = new (wrapper(Constructor, [1,2]));
alert(o.foo);

We take a function and arguments and create a function that applies the arguments to that function with the this scope.

Then if you call it with the new keyword it passes in a new fresh this and returns it.

The important thing is the brackets

new (wrapper(Constructor, [1,2]))

Calls the new keyword on the function returned from the wrapper, where as

new wrapper(Constructor, [1,2])

Calls the new keyword on the wrapper function.

The reason it needs to be wrapped is so that this that you apply it to is set with the new keyword. A new this object needs to be created and passed into a function which means that you must call .apply(this, array) inside a function.

Live example

Alternatively you could use ES5 .bind method

var wrapper = function(f, args) {
    var params = [f].concat(args);
    return f.bind.apply(f, params);
};

See example

Tags:

Javascript