1

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

3
  • window is a reserved word in javascript, why are you using it? Commented Mar 5, 2013 at 20:17
  • To gain access to variables in the global scope Commented Mar 5, 2013 at 20:19
  • 2
    @ryan: window is definitely not a reserved word. Seems clear that OP is making reference to the global object,. Commented Mar 5, 2013 at 20:21

1 Answer 1

2

window.objects[0] is a string.
You want to get the property of window named by that string:

window[window.objects[0]]
Sign up to request clarification or add additional context in comments.

6 Comments

What does that have to do with creating objects by string name?
he means you can do new window[window.objects[0]]( )
...although new window[objects[0]]( ) is shorter and just as good
hm, i tried window[window.objects[0]] and also window[objects[0]] and they both came back as undefined
window[window.objects[0]] would return window['string1'] which doesn't exist since it's in the objects array of window
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.