is there a way to access a non-global shadowed variable in javascript

主宰稳场 提交于 2020-01-11 10:41:09

问题


I'm currently learning javascript scope and was just wondering whether it is possible to access a non-global shadowed variable in javascript? i.e. in the example below, the variable a that equal to 10 in the aFunc function

var a = 1;
function aFunc(){
    var a = 10;
    function innerFunc(){
        var a = 100;
        console.log("innerFunc a = " + a);
        console.log("is it possible to access outer function's a variable?");
        console.log("global a = " + window.a);
    }
    innerFunc();
}
aFunc();

ps - I understand naming your variables with the same name is very bad practice, but I guess I asked this question out of curiosity


回答1:


No you cannot do this with Javascript at least. There is no way that you can access it since you have intentionally shadowed it (accept it as a feature ;)). Javascript doesn't have a mechanism to access variables in lexical scope (one step up).



来源:https://stackoverflow.com/questions/44941421/is-there-a-way-to-access-a-non-global-shadowed-variable-in-javascript

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