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(...)
airportyh
  • 21,948
  • 13
  • 58
  • 72
  • Dup: http://stackoverflow.com/questions/813383/how-can-i-construct-an-object-using-an-array-of-values-for-parameters-rather-tha – Crescent Fresh Sep 03 '09 at 01:02

3 Answers3

1

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
  • 23,327
  • 2
  • 33
  • 27
1

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.

Community
  • 1
  • 1
Crescent Fresh
  • 115,249
  • 25
  • 154
  • 140
  • Un-accepted this answer because there's now a great answer at http://stackoverflow.com/questions/813383/how-can-i-construct-an-object-using-an-array-of-values-for-parameters-rather-tha#answer-813401 – airportyh Nov 10 '10 at 18:28
0

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?

Community
  • 1
  • 1
airportyh
  • 21,948
  • 13
  • 58
  • 72