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!
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.
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With