Wilt Wilt - 5 months ago 12
Javascript Question

Argument gets lost when using bind apply with array arguments

I used this answer here to construct a new class instance by passing array arguments using the following code:

new ( Cls.bind.apply( Cls, arguments ) )();


But when one of my arguments is an array the values get lost during construction

You can check an example that demonstrates this in this CodePen

In the example I pass the third argument
properties
:

var properties = [
{ name: "first", value: "1" },
{ name: "second", value: "2" },
{ name: "third", value: "3" }
];


But the properties in the result is
undefined
.

Apparently something goes wrong here, but what and why?

Answer

Your code is almost correct but you need to pass an additional argument to your factory() : factory(undefined, name, description, properties)

This is highlighted in the SO answer you link to in your question:

The anything parameter doesn't matter much, since the new keyword resets f's context. However, it is required for syntactical reasons. Now, for the bind call: We need to pass a variable number of arguments, so this does the trick: var f = Cls.bind.apply(Cls, [anything, arg1, arg2, ...]); result = new f();