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,618
  • 25
  • 40

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
  • 572,313
  • 128
  • 898
  • 1,281