Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 807
jaysonp Avatar asked Jan 04 '11 03:01

jaysonp


People also ask

How do you create an instance of a class dynamically in Python?

Classes can be dynamically created using the type() function in Python. The type() function is used to return the type of the object. The above syntax returns the type of object.

What is dynamic method in PHP?

To call a method dynamically means that we can assign method name to any variable and call the method using that variable, either in switch case of if else block or anywhere depending on our requirement.


1 Answers

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");
like image 192
ChaosPandion Avatar answered Oct 26 '22 23:10

ChaosPandion