Wilt Wilt - 1 year ago 65
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

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

But the properties in the result is

Apparently something goes wrong here, but what and why?

Answer Source

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();

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download