Click here to Skip to main content
14,977,402 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have been having some confusion with closures, the following is the scenario, problem and code. Please run your code in Chrome if you want to actually test the code

So I have created deep nested functions. There are four nested functions function four() is nested -> inside function three() nested -> inside function two() nested -> inside function one().

JavaScript
function one() {
  var oneVar = "_oneVar_";
  return function two() {
    var twoVar = "_threeVar_";;
    return function three() {
      var threeVar = "_threeVar_";
      return function four() {
        threeVar;
        twoVar;
        oneVar;
      }
    }
  }
}
// Run code in Chrome specifically to check [[Scopes]]
// Other browser like Firefox does not show Scopes
console.dir(one);
console.dir(one());
console.dir(one()());
console.dir(one()()());


So when I run the code and inspect the results in Chrome Developer tools I observed closures in [[Scopes]] were not only created for function four but also for function three and function two. It looks as if the when local variables declared that were out of that function scope the function kept moving out of its functional scope and continued searching for the local variable and in each functional scope it kept passing it created closures for each function until it did found the variable.

So what is happening under the hood exactly ? Now I am not sure if this behavior is related JavaScript or is it something to do with The Chrome Dev tools.

What I have tried:

I have googled by havent found an answer yet :(
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900