0

I am trying to learn JS and With Respect to javascript closures I have a question -

function fooOuter(){
   var a = 10;
   var b = 20;
   return function fooinner(x){
      return a + b + x;
   };
}

Does this mean that the inner functions in Javascript stores references to all the variables that lie in the same scope. i.e. In this this case, does fooinner store references of variables a and b.

vol7ron
  • 40,809
  • 21
  • 119
  • 172
Student
  • 4,481
  • 8
  • 27
  • 32

4 Answers4

3

Effectively, yes. There is a so-called "scope chain" that is created by the runtime, and links in the chain are only freed when no longer referenced. fooinner() has its own scope, with a "parent scope" link to the scope of fooOuter(), and so on -- this is fooinner()'s scope chain.

The variables used by fooinner() and defined outside of it will therefore continue to live for as at least as long as that particular function object lives.

cdhowie
  • 158,093
  • 24
  • 286
  • 300
0

fooInner will retain the values of a and b for each instance of fooInner returned. In other words each function will equate to 10 + 20 + x. In effect it is a closure and a partial.

Jerry Hoerig
  • 146
  • 9
0

This is some facts I got from a training. I hope this help

When the function is created, it is assigned a [[scope]] property which references the variables of the outer lexical scope and prevents them from being garbage collected. Therefore the closure is formed on function creation.

The closure references variables not values. Since every function invocation takes place in a unique execution context, we guarantee the uniqueness of the argument variable across successive invocations.

Its important to note that the closure creation process is identical for every function, and every function creates a closure

Agus
  • 1,604
  • 2
  • 23
  • 48
0

Yes it pretty much does that.

Simply spoken, a closure is nothing else than a Context which has access to its parent context data. There are tons of good explanations either on Stackoverflow or on the Web.

But without going into greater detail, the second your inner function fooinner gets parsed, the ECMAscript interpreter internally sets up a link to the outer function (we call it Activation Object respectively Lexical Environment Record).

jAndy
  • 231,737
  • 57
  • 305
  • 359