tags:

views:

525

answers:

6
someFunction(link) {
  someOtherFunction('div' + link);
}

By calling someFunction("Test"), the string "divTest" gets passed to someOtherFunction(). But I want the value of the variable "divTest" to be passed.

How can that be done?

+2  A: 

You should be able to accomplish this with the 'eval' function.

wybiral
A: 

As wybiral said, all you need is eval:

someFunction(link) {
  someOtherFunction(eval('(div' + link + ')');
}

Basically what it does is evaluates the contents of a string as code. Obviously eval is a dangerous little tool since it allows executing arbitrary code so take care when using it.

DrJokepu
Can you explain the logic behind the inner most set of parenthesis?
chipotle_warrior
RyOnLife: They don't serve any specific purpose in this example but it is good practice to put all your eval strings in parentheses. Here's why: http://techiella.wordpress.com/2008/09/04/javascript-eval/
DrJokepu
+5  A: 

For this kind of dynamic construction/access of variable names you should use the alternative object notation where:

object.member === object["member"]

This way you could construct your variable name as a string and use it inside square brackets for accessing object members.

Ionuț G. Stan
+2  A: 

eval will do this, but it's usually indicative of some other problem with the program when you want to synthesize identifiers like this. As Ionut says it's better to use the [] notation. I like to link to this whenever questions like this come up.

Logan Capaldo
+4  A: 

Make your variables members of an object. Then you can use [] to access the objects members using a string:

var byname = {
  divabc: ...,
  divxyz: ...
};

function someFunction(link) {
  someOtherFunction(byname['div'+link]);
}

someFunction('abc'); // calls someOtherFunction(byname.divabc)
sth
+1  A: 

Try this:

var divFoo = "bar";
function someFunction(link) {
    someOtherFunction(this['div' + link]);
}
function someOtherFunction(value) {
    alert(value);
}
someFunction("Foo");
Gumbo