Alex Rivera | Logout

How can I construct an object using an array of values for parameters, rather than listing them out, in JavaScript?

Asked 2009-05-01T21:25:51.287
11

Is this possible? I am creating a single base factory function to drive factories of different types (but have some similarities) and I want to be able to pass arguments as an array to the base factory which then possibly creates an instance of a new object populating the arguments of the constructor of the relevant class via an array.

In JavaScript it's possible to use an array to call a function with multiple arguments by using the apply method:

namespace.myFunc = function(arg1, arg2) { //do something; }
var result = namespace.myFunc("arg1","arg2");
//this is the same as above:
var r = [ "arg1","arg2" ];
var result = myFunc.apply(namespace, r);

It doesn't seem as if there's anyway to create an instance of an object using apply though, is there?

Something like (this doesn't work):

var instance = new MyClass.apply(namespace, r);
Edit
Report

2 Answers

15

Try this:

var instance = {};
MyClass.apply( instance, r);

All the keyword "new" does is pass in a new object to the constructor which then becomes the this variable inside the constructor function.

Depending upon how the constructor was written, you may have to do this:

var instance = {};
var returned = MyClass.apply( instance, args);
if( returned != null) {
    instance = returned;
}

Update: A comment says this doesn't work if there is a prototype. Try this.

function newApply(class, args) {
    function F() {
        return class.apply(this, args);
    }
    F.prototype = class.prototype;
    return new F();
}

newApply( MyClass, args);
answered 2009-05-01T21:35:01.543
0

what about a workaround?

function MyClass(arg1, arg2) {

    this.init = function(arg1, arg2){
        //if(arg1 and arg2 not null) do stuff with args
    }

    init(arg1, arg2);
}

So how you can:

var obj = new MyClass();
obj.apply(obj, args);
answered 2009-05-01T21:41:28.097

Your Answer