问题
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