HAYCORN — 1 June 2010

Calling a constructor with an array of arguments

Sometimes it’s useful to use JavaScript’s apply() function to call a function that usually takes separate arguments with a single array argument instead. That is, instead of

obj.foo(1, 2, 3);

you can do

obj.apply(obj, [1, 2, 3]);

Unfortunately, there’s no way to use apply() with a constructor. However, it turns out that you can exploit the fact that constructors can be chained using apply(...) to achieve this, although this requires the creation of a proxy class. The construct() function below lets you do:

// The following two lines are equivalent
var f1 = construct(Foo, [2, 3]);
var f2 = new Foo(2, 3);

The construct() function:

function construct(klass, args) {

  function F() {
    klass.apply(this, arguments[0]);
  };

  F.prototype = klass.prototype;

  return new F(args);

}

Some sample code that uses it:

function Foo(a, b) {
  this.a = a; this.b = b;
}

Foo.prototype.dump = function() {
  console.log("a = ", this.a);
  console.log("b = ", this.b);
};

var f = construct(Foo, [7, 9]);

f.dump();