Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 360
Wilt Avatar asked Nov 27 '25 07:11

Wilt


1 Answers

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

like image 147
Michele Ricciardi Avatar answered Nov 29 '25 20:11

Michele Ricciardi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!