有没有办法在javascript中访问非全局阴影变量 [英] is there a way to access a non-global shadowed variable in javascript

查看:55
本文介绍了有没有办法在javascript中访问非全局阴影变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习javascript范围,只是想知道是否有可能在javascript中访问非全局阴影变量?即在下面的示例中,变量aaFunc函数中等于10

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-我知道用相同的名字命名变量是非常不好的做法,但是我想我出于好奇而问了这个问题

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

推荐答案

否,至少不能使用Javascript做到这一点.由于您故意将其阴影(将其作为功能部件接受),因此无法访问它. Javascript没有一种机制可以访问词汇范围内的变量(向上移动).

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

这篇关于有没有办法在javascript中访问非全局阴影变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆