1

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?

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
cicada
  • 13
  • 2
  • 4
  • Note: you don't have a list of variables, you have _one_ variable that references an object with several properties. Regarding your `varGetter()` method, what should it do if asked for the value of a property that doesn't exist, e.g., `myApp.varGetter("fred")`? – nnnnnn Dec 24 '14 at 00:21
  • Thanks for your answer. The relevant code knows always what to ask but i want this to be done indirectly. – cicada Dec 24 '14 at 00:34

4 Answers4

2

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];
steo
  • 4,586
  • 2
  • 33
  • 64
  • 1
    Thanks for your answer. Making some tests in Scratchpad, your suggestion seems to work :-) – cicada Dec 24 '14 at 00:52
1

You can use myApp[aName] to use a variable as a property name:

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

 varGetter: function(aName) {
  return myApp[aName];
 }
};

console.log(myApp.varGetter("var1")); // true

Also, to avoid hardcoding myApp in your function you can replace it with this[aName].

akxlr
  • 1,142
  • 9
  • 23
0

You can access gloval variables via the window variable. Example:

var foo = 'asdf';
alert(window['foo']);

To get json variables, use the same notation:

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

function varGetter(name) {
    return myApp[name];
}

EDIT: Misread the question.

Chloe
  • 483
  • 4
  • 14
0

If what you want to do is encapsulation (keeping variables private), you should use the module pattern, which would give you that :

var myApp = (function(){
    //you can't access those variable doing myApp.var1 for example
    var data = {};
    data.var1 = true;
    data.var2 = false;
    data.var3 = true;
    data.var4 = false;

    //then explicitly make your getter/setter
    function varGetter(varName){
        return data[varName];
    }

    //finally, return an object into myApp, out of this closure
    return {
        varGetter : varGetter
    };
})()
topheman
  • 7,422
  • 4
  • 24
  • 33