Professor: I t does, but not a reference to the count() fu nction. Note that the expres-
sion count() is not a reference but a function invocation because it has parentheses
at the end. So, in fact, the return value of the count() function is assigned to the
variable countThi s, which is a reference to the inner anonymous function.
In JavaScript, not only a function definition but also a function invocation creates
a new function object. The new function object holds the local variables for that
specific invocation and is added to the existing scope chain, which represents the scope
for th at particular function invocation. T he trick of the count() function is that it
defines another fun ction within its body and retu rns a reference to it. As long as you
keep a reference to the returned anonymous function, the anonymous function object
persists in m emory and so must the count() function object because it is a part of the
anonymous function’s scope chain.
We can invoke the co unt() function once mor e, an d again store a refe rence to the
returned anonymous function, this time to a variable countThat:
var countThat = count();
By doing that, we c reate yet another scope chain and append it to the existing one.
Note that the existing scope chain only contains the global object because c ount() is
invoked within global scope. Exactly the same was true with th e first invocation of the
count() function, and we end up with two scope chains, bo th starting with the global
object. Here’s a n illustration of the two scope chains of the two objects crea te d by th e
two invocations of count().
global
count
var i;
countThis
count
var i;
countThat
The two gr ay areas represent scopes of both i variables, and countThis and count
That are references to the two anonymous function objects that we created when we
called count() two times. What we can do now is call any of the two anonymous
functions, which sit on the top of the two scope chains. A call of th e left one will
incremen t and return the left i and a call of the right one will increment and return the
right i. For example:
countThis(); //The left i is now 1
countThat(); //The right i is now 1
countThis(); //The left i is now 2
countThis(); //The left i is now 3
console.log(countThis());//Writes 3 and increments the left i to 4:
console.log(countThat());//Writes 1 and increments the right i to 2:
202 Meeting 10. Understa nding Functions