Evaluate a string as an object (without eval() )?

C

conzett

I have the name of an object in the form of a string. Is there a way
to access it as an object without eval? basically can I do this:


function foo(){
this.bar = function(){
alert("test")
}
}

var myFoo = new foo();
var examplVar = "myFoo";

eval(examplVar).bar();

//it alerts test


without having to use eval?
Sorry if this is a noob question I don't usually use javascript.
 
D

d d

I have the name of an object in the form of a string. Is there a way
to access it as an object without eval? basically can I do this:
var myFoo = new foo();
var examplVar = "myFoo";

eval(examplVar).bar();

//it alerts test


without having to use eval?

Don't be afraid of eval, it's not as evil as they say.
In this case you don't need it though.

window[examplVar].bar();

~dd
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top