thanks to wonderful responses to this question I understand how to call javascript functions with varargs.
now I\'m looking to use apply with a constructor
You can exploit the fact that you can chain constructors using apply(...)
to achieve this, although this requires the creation of a proxy class. The construct()
function below lets you do:
var f1 = construct(Foo, [2, 3]);
// which is more or less equivalent to
var f2 = new Foo(2, 3);
The construct()
function:
function construct(klass, args) {
function F() {
return 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();