dynamic object construction in javascript?

Viewed 12475

When I want to call a function in javascript with arguments supplied from elsewhere I can use the apply method of the function like:

array = ["arg1", 5, "arg3"] 
...
someFunc.apply(null, array);

but what if I need to call a constructor in a similar fashion? This does not seem to work:

array = ["arg1", 5, "arg3"] 
...
someConstructor.apply({}, array);

at least not as I am attempting:

template = ['string1', string2, 'etc'];
var resultTpl = Ext.XTemplate.apply({}, template);

this does not work wither:

Ext.XTemplate.prototype.constructor.apply({}, template);

Any way to make that one work? (In this particular case I found that new Ext.XTemplate(template) will work, but I am interested in the general case)

similar question but specific to built-in types and without an answer I can use: Instantiating a JavaScript object by calling prototype.constructor.apply

Thank you.

Edit:

Time has passed and ES6 and transpilers are now a thing. In ES6 it is trivial to do what I wanted: new someConstructor(...array). Babel will turn that into ES5 new (Function.prototype.bind.apply(someConstructor, [null].concat(array)))(); which is explained in How to construct JavaScript object (using 'apply')?.

4 Answers

Since the original question is quite old, here's a simpler methods in practically any modern browser (as of writing, 2018, I'm counting Chrome, FF, IE11, Edge...).

var template = ['string1', string2, 'etc'];
var resultTpl = Object.create(Ext.XTemplate.prototype);
Ext.XTemplate.apply(resultTpl, template);

Those two lines also explain how the new operator basically works.

Related