airportyh
airportyh

Reputation: 22668

Instantiate an object by calling constructor with parameter list using apply?

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

Answers (3)

Crescent Fresh
Crescent Fresh

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

Eldar Djafarov
Eldar Djafarov

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

Related Questions