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

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top