Create an object by calling a constructor with a parameter list using apply?

Given the function / type declaration:

function Person(name, ... other args ...){
    this.name
    ... other init code ...
}

      

I would like to be able to call the Person constructor with an array of arguments that will be applied to it. I could do:

Person.apply(this, args)

      

Except it doesn't instantiate a person, it just calls it a function. Is there a way you call it this way, but in a "new" context, like this:

new Person(...)

      

+2


source to share


3 answers


Another thread came up with the correct answer: How can I construct an object using an array of values ​​for the parameters instead of listing them in JavaScript?



0


source


Cause:

var newInstance=Person.apply({}, args);

      



You will apply a constructor to an empty object. But you should be aware that this will not really be an instance of the class. If you want to supply an instance of a class, you must supply a clone of the prototype as the first parameter.

+1


source


Before that, it was quite long back and forth .

In short, no, you cannot do this and make it work in all cases. There are some very valuable code examples of how you can accomplish this in this link, but each has a case where it breaks. This may be enough for you.

+1


source







All Articles