If I have a sting such as "AppNamespace.SomeObject.ClassName" and I know that the string represents and actual constructor function, what is the best/recommend way of getting that to use in a statement like var foo = new AppNamespace.SomeObject.ClassName?
I could do:
var s = "AppNamespace.SomeObject.ClassName"
var foo = new (eval(s))
or something like:
var parts = "AppNamespace.SomeObject.ClassName".split(".")
var foo = new (window[parts[0]][parts[1]][parts[2]])
but I’m wondering if there are better solutions that don’t involve eval or having to split the string and loop through its parts. Does anyone have any ideas? If not, based on the two solutions I’ve proposed, what are the pros and cons of each?
You could do…
jsFiddle.
On older browsers, you could shim
reduce().This code splits the string by the period (
.) and then iterates over each from left to right, starting withwindowas the start object (change it if it isn’t) and getting each sub property until it arrives with the far right (ClassNamein your example).The
new (...)instantiates this object.You could write it as a reusable function…