3
If I have a Javascript function and want to call it by passing a list of arguments, use apply
:
var x = f(1,2,3);
var x = f.apply(null, [1,2,3]);
For the first time, I came across a case where I need to call one builder with a list of arguments, and the first thing I tried (even suspecting it would go wrong) was to simply do the same:
var x = new f(1,2,3);
var x = new f.apply(null, [1,2,3]);
And in fact it didn’t work... Is there any way to do that? I have to create several objects, in a loop, and I was forced to do so:
var x = new f(lista[0], lista[1], lista[2]);
That is not so bad in the case of a builder with only 3 parameters, but I wonder if there is a more concise or "elegant means".
Interesting! Only that way I’d have to do
construtor.apply(null, [f].concat(lista))
. But nothing a little adjustment won’t fix:function construtor(Construtor, args) { return new (Construtor.bind.apply(Construtor, [null].concat(args))); }
and to useconstrutor(f, lista)
. Example– mgibsonbr
@mgibsonbr good fit. The
.unshift()
would also (http://jsfiddle.net/60snrx9L/2/) but your version uses less characters :)– Sergio
The problem of
unshift
is that it causes a side effect on the list passed as argument, while theconcat
is being used in a new list.– mgibsonbr
@mgibsonbr truth, well seen.
– Sergio