简体   繁体   English

有没有办法在 JavaScript 中访问阴影变量?

[英]Is there a way to access a shadowed variable in JavaScript?

 var a=1;   //first one
 function x() {
    var a=2;  // second
    function y() {
       var a=3;  // third one
    }
 }

Is there any way that function y() can access the second var a ? function y()有什么方法可以访问第二个var a吗? I know it can access first one via window.a .我知道它可以通过window.a访问第一个。

As-written?写的? No.不。

If you're not dead-set on naming each one a , then you can easily reference it.如果您不介意将每个命名a ,那么您可以轻松地引用它。 The other solution would be to capture the outside variable within another variable, the trick being to not have the same variable name being referenced in the outside scope, from the inside scope.另一种解决方案是在另一个变量中捕获外部变量,技巧是在外部范围内不从内部范围引用相同的变量名。

window.a = 1;
function x() {
    var a = 2,
        inner_a = a,

        y = function () {
            var old_a = inner_a,
            // a is equal to the closest var assignment ie: inside x()
                a = 3;
        };
 }

or to pass it into the construction of a new function through closure或者通过闭包将其传递到新函数的构造中
(immediately-invoking function) (立即调用函数)

window.a = 1;
function x() {
    var a = 2;
    var y = (function (old_a) {
        return function () { var a = 3; }; 
        // this inner function has access to "old_a", through closure
    }(a));
}

This is a pattern that is preferred for several use-cases, when mixing JS with browser-functionality (ie: the DOM and DOM events, loops which assign timers or callbacks, AJAX responses, et cetera).当混合 JS 与浏览器功能(即:DOM 和 DOM 事件、分配计时器或回调的循环、AJAX 响应等)时,这是多个用例的首选模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM