javascriptoop

How to construct a class the name of which is held in a variable?


I would like to create a new object in JavaScript (using simple inheritance) such that the class of the object is defined from a variable:

var claſs = 'Person';
var inst = new ⟨claſs⟩();

any ideas?


Solution

  • You can do something like

    function Person(){};
    var name = 'Person';
    var inst = new this[name]
    

    The key is just referencing the object that owns the function that's the constructor. This works fine in global scope but if you're dumping the code inside of a function, you might have to change the reference because this probably wont work.

    EDIT: To pass parameters:

    function Person(name){alert(name)};
    var name = 'Person';
    var inst = new this[name]('john')