0

I'm trying to understand closures in javascripts. A closure is the local variables for a function — kept alive after the function has returned [reference].

In many references I saw they consider parent function when describing closure of a function. But according to the example below I think a function can access not only the variables in the parent function, but also in the grand parent and above..

Can someone explain if what I think is correct or not? Thank you in advance..

test1 = function() {
  var x = 10;
  return function(){
    alert(++x);
  };
}

test2 = function() {
  var x = 10;
  return function(){
    return function(){
       alert(++x);
    }
  };
}

t1 = test1();
t1(); //11
t1(); //12
t2 = test2()();
t2(); //11
t2(); //12
Community
  • 1
  • 1
Sampath Liyanage
  • 4,776
  • 2
  • 28
  • 40
  • 1
    I think you are missing some code at the top for `test1` – KJ Price Oct 31 '14 at 13:38
  • 2
    If a parent function can access a variable then so can a child. It's not dependent on a variable being *explicitly* defined in the *immediate* parent. – Dave Newton Oct 31 '14 at 13:39
  • 1
    The only thing that matters here is the scope of the variable (where the variable was defined). You can access as high up as the variable is defined. – KJ Price Oct 31 '14 at 13:41

1 Answers1

1

Yes, each scope has access to its parent scope, which is a transitive relation - when your parent scope can access the variables from your grand parent, and you can access the variables from your parent, then you can also access those of your grandparent (and its parents).

Bergi
  • 630,263
  • 148
  • 957
  • 1,375