Accessing variables indirectly [duplicate]

北战南征 提交于 2019-12-02 04:51:24

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];

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].

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.

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
    };
})()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!