jaysonp
jaysonp

Reputation: 101

instantiate dynamic class

In Javascript, how do you instantiate a new class dynamically without using eval() and pass in an argument? For example, let's say I want to create a new CatViewController and pass in "kitten", how would I do that?

var myClassname = "CatViewController";
var cat = new myClassname("kitten");

It should resolve to:

var cat = new CatViewController("kitten");

Thanks!

Upvotes: 10

Views: 5635

Answers (2)

Will
Will

Reputation: 9

@Matthew - If you have reference to the window scope you should be good to go, right? Just use the window reference instead of the this keyword. Seems to be working for me. However I'm very curious if there are any downfalls to this approach since I'm currently using it in a project. Here is a demo based on your previous demo.

Upvotes: 0

ChaosPandion
ChaosPandion

Reputation: 78272

As long as the function is within scope you can do this:

var cat = new this[myClassname]("kitten");

Another similar way:

var classes = {
    A: function (arg) {

    },
    B: function (arg) {

    },
    C: function (arg) {

    }
};

var a = new classes["A"]("arg");

Upvotes: 8

Related Questions