Search code examples
javascriptindirection

Accessing variables indirectly


Within my code (javascript in a firefox extension), i have a list of some variables, like this:

var myApp = {
 var1: true,
 var2: false,
 var3: true,
 var4: false
};

I want to access these variables to get their value indirectly using a function:

var myApp = {
 var1: true,
 var2: false,
 var3: true,
 var4: false,

 varGetter: function(aName) {
  // code
  return myApp.aName.value;
 }
};

I call this function like this for example:

if(myApp.varGetter("var2")) {alert("true")};

Now, how this function can be implemented to do what i want?


Solution

  • The problem is that you are trying to access a property with the dot notation and the variable.

    myApp.aName.value;
    

    this sometimes creates new property or returns undefined

    You should use this notation instead

    myApp[aName];