javascript syntax question
Author
Discussion

Code Monkey

Original Poster:

3,318 posts

287 months

Tuesday 20th September 2005
quotequote all
anyone know if it is possible to do the following?

function canUdo(var1, var2){
if (object.var1 == var2){
//do stuff

etc.....

object is already defined in file canUdo is within, function is called from outside with possibility of a few different properties of the object.

if not i will put in a case statement or an if else structure to handle it, but just wondering, anyone done this before?

cheers,

robbieduncan

1,993 posts

266 months

Tuesday 20th September 2005
quotequote all
I'm a bit unclear on what you are trying to do. Is var1 a string with the name of the instance variable in object? If so you can do exec('object.'+var1) which will returnt the value of var1 in object where var1 is the name of the instance variable.

GreenV8S

31,024 posts

314 months

Tuesday 20th September 2005
quotequote all
Yes.

Edited to add: yes, if the object you are referring to is accessible to the function. If you want to access a member variable/function identified by a string variable, the syntax is:

object[var1]

>> Edited by GreenV8S on Tuesday 20th September 11:06

Code Monkey

Original Poster:

3,318 posts

287 months

Tuesday 20th September 2005
quotequote all
thank you both, much smoother way of writing it.

cheers for the help

GreenV8S

31,024 posts

314 months

Tuesday 20th September 2005
quotequote all
Incidentally, the reason this isn't obvious is because the thing you're trying to do isn't normal. It may be this is a good and wholesome approach to take, but it may also be that you could remove the need for this by improving the design. For example, add a method to your object to do whatever it is you are trying to do to it, or retrieve the property that you're trying to access externally within the caller rather than passing the property *name* in.