0

Noob question here. Please see code below. Where can I read more on this? I mean, this_variable gets 100. All subsequently defined functions seem to be able to access this variable and get it's value, but I wonder how deep does this work? I'm working on a Chrome extension and the damn thing only works with callbacks; I need to be able to access stuff within a pretty deeply nested callback and I need to be sure that what I write is reliable and will remain consistent.

(function(){

    this_variable = 100;

    (function(){
        (function(){
            (function(){
                (function(){
                    (function(){

                        tadaaa = this_variable;
                        console.log(tadaaa); // sais 100                

                    }());
                }());
            }());
        }());
    }());
}());
Silviu-Marian
  • 10,565
  • 6
  • 50
  • 72

5 Answers5

6

There is no limit. Though if you're nested deeply enough to worry about a limit, I would question the overall design.

James Montagne
  • 77,516
  • 14
  • 110
  • 130
2

As long as a variable is 'in scope' it can be accessed (presuming it's not hidden). You can nest as much as you like. See here for scoping and closure reference from MDN.

Rich O'Kelly
  • 41,274
  • 9
  • 83
  • 114
2

As deeply as you want. The name for the concept is closures and it is the most important concept when programming advanced javascript.

Community
  • 1
  • 1
George Mauer
  • 117,483
  • 131
  • 382
  • 612
1

As far as you goes..

It might be slower at some point, but should still be accessible all the way through your callbacks.

f2lollpll
  • 997
  • 6
  • 15
0

Javascript uses function scoping. The rule is if a variable is set within the top level function, then all of the nested functions within the top level function have access to that variable. If a variable is declared within a nested function, then the top level function(s) will not have access to that variable.

//Immediately invoked function that scopes jQuery and outside code cannot access
$(function() {
    //top-level function
    function test() {
        var a = true;
        //nested function
        function nestedTesting() {
            //The nested function has access to a
            console.log(a);
            var b = false;
        }
        nestedTesting();
        //The top level function does not have access to b
        console.log(b);
    }
    test();
});

Expected Result:

  1. true
  2. Uncaught ReferenceError: b is not defined
Greg Franko
  • 1,780
  • 15
  • 14