views:

61

answers:

2

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(...)
+1  A: 

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.

Eldar Djafarov
I tried this, but had to modify it to work: var newInstance = {}; Person.apply(newInstance, args);
toby
+1  A: 

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.

Crescent Fresh