In the client, I have declared a namespace and various classes within different namespaces. The challenge arises when I receive a string from the server upon page load containing "dotted" namespace.class names, and I need to obtain an instance of one of these classes.
Currently, my approach involves using eval
for this purpose. However, I have noticed that it leads to memory leaks. Hence, I am exploring alternative methods to instantiate a declared object based solely on its name. Simply attempting something like
var obj = "myNamespace.myObjectName"();
does not yield the desired result.
If I have an object name stored as a string variable, I can utilize the eval()
function to generate an instance of that object:
window["myNamespace"] = {};
myNamespace.myObjectName = function() { /* blah */ };
var name = "myNamespace.myObjectName";
var obj = eval("new " + name + "()");
However, due to various reasons, I prefer not to use eval
. Is there a way to create an object by its name without resorting to eval
?