I have an array of strings which define class names. I would like to instantiate these classes using the string name. I have tried to use window but I haven't been able to do it.
The structure is
var objects = ['string1', 'string2'];
So the window would look like
window [
objects [
'string1',
'string2'
]
]
I have tried:
new window['objects'][0];
But that threw the string is not a func error.
Anyone know how to do this?
Thanks
asked Mar 5, 2013 at 20:15
Cjmarkham
9,7336 gold badges52 silver badges85 bronze badges
1 Answer 1
window.objects[0] is a string.
You want to get the property of window named by that string:
window[window.objects[0]]
answered Mar 5, 2013 at 20:16
SLaks
891k182 gold badges1.9k silver badges2k bronze badges
Sign up to request clarification or add additional context in comments.
6 Comments
mellamokb
What does that have to do with creating objects by string name?
Dave
he means you can do new window[window.objects[0]]( )
Dave
...although new window[objects[0]]( ) is shorter and just as good
Cjmarkham
hm, i tried window[window.objects[0]] and also window[objects[0]] and they both came back as undefined
Cjmarkham
window[window.objects[0]] would return window['string1'] which doesn't exist since it's in the objects array of window
|
lang-js
windowis a reserved word in javascript, why are you using it?windowis definitely not a reserved word. Seems clear that OP is making reference to the global object,.