HAYCORN — 1 June 2010

Calling a constructor with an array of arguments

Some­times it’s useful to use JavaScript’s apply() func­tion to call a func­tion that usually takes sep­a­rate ar­gu­ments with a single array ar­gu­ment 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 con­struc­tors can be chained using apply(...) to achieve this, al­though this re­quires the cre­ation of a proxy class. The construct() func­tion below lets you do:

// The fol­low­ing two lines are equiv­a­lent
var f1 = construct(Foo, [2, 3]);
var f2 = new Foo(2, 3);

The construct() function:

func­tion construct(klass, args) {

 func­tion F() {
 klass.apply(this, arguments[0]);

 F.prototype = klass.prototype;

 return new F(args);


Some sample code that uses it:

func­tion 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]);