Skip to content Skip to sidebar Skip to footer

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

Solution 1:

As-written? No.

If you're not dead-set on naming each one a, then you can easily reference it. 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).


Post a Comment for "Is There A Way To Access A Shadowed Variable In JavaScript?"