3

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 one of my arguments is an array and 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?

Community
  • 1
  • 1
Wilt
  • 41,477
  • 12
  • 152
  • 203

1 Answers1

4

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

Michele Ricciardi
  • 2,107
  • 14
  • 17