Reputation: 22668
Given a function/type declaration like this:
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 to be applied to it. I could do:
Person.apply(this, args)
Except that this doesn't instantiate a person, it merely calls it as a function. Is there any way you call it in this way but in the "new" context, i.e behaving like:
new Person(...)
Upvotes: 2
Views: 723
Reputation: 22668
Correct answer has emerged on the other thread: How can I construct an object using an array of values for parameters, rather than listing them out, in JavaScript?
Upvotes: 0
Reputation: 116980
There was a rather lengthy back and forth about this before.
In short, no you cannot do this and have it work for all cases. There are some very valuable code examples of how you can accomplish it in that link, but each has a case where it breaks. That may be good enough for you however.
Upvotes: 1
Reputation: 24667
Of cause:
var newInstance=Person.apply({}, args);
You will apply constructor to empty object. But you should be aware that this will not be really instance of class. If you want to bet instance of class you should put a clone of prototype object as a first parametr.
Upvotes: 1