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(...)
source to share
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?
source to share
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.
source to share
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.
source to share