Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic instantiation in JavaScript

Tags:

javascript

Apart from eval(`o = new ${className}(${args.join(", ")})`), is there any other way to instantiate an object using variable argument list?

E.g.: var foo = instantiate(className, [arg1, arg2, ...])

like image 522
Alexey Lebedev Avatar asked Feb 17 '11 13:02

Alexey Lebedev


2 Answers

You can instantiate an object with a variable argument list like this:

function instantiate(className, args) {
    var o, f, c;
    c = window[className]; // get reference to class constructor function
    f = function(){}; // dummy function
    f.prototype = c.prototype; // reference same prototype
    o = new f(); // instantiate dummy function to copy prototype properties
    c.apply(o, args); // call class constructor, supplying new object as context
    o.constructor = c; // assign correct constructor (not f)
    return o;
}

Side note: you may wish to pass a direct reference to the class constructor function:

var foo = instantiate(Array, [arg1, arg2, ...]);
// Instead of:
var foo = instantiate("Array", [arg1, arg2, ...]);

... which makes this compatible with non-global functions.

like image 80
David Tang Avatar answered Nov 04 '22 19:11

David Tang


Using Object.create() in ES5:

function instantiate(constructor, args) {
    var instance = Object.create(constructor.prototype);
    constructor.apply(instance, args);
    return instance;
}

Using the spread operator in ES6:

var foo = new constructor(...args);
like image 39
Alexey Lebedev Avatar answered Nov 04 '22 20:11

Alexey Lebedev