mjmitche mjmitche - 2 years ago 316
Javascript Question

Javascript closure

The following program returns "local" and, according to the tutorial I

m reading, it is designed to demonstrate the phenomenon of
closure`

What I don`t understand is why, at the end, in order to call parentfunction, it assigns it to the variable "child" and then calls "child."

Why doesn`t it work by just writing parentFunction(); at the end?

var variable = "top-level";
function parentFunction() {
var variable = "local";
function childFunction() {
print(variable);
}
return childFunction;
}

var child = parentFunction();
child();

Answer Source

The amazing part about closures is that an inner function (in this case, childFunction) can refer to variables outside of its scope (in this case, variable). parentFunction doesn't return the result of childFunction, but an actual reference to the function!

This means that when you do the following...

var child = parentFunction();

...now, child has a reference to childFunction, and childFunction still has access to any variables it had when the function was created, even if they no longer exist.

In order to have parentFunction call childFunction, you'd need to change your code as follows:

From...

return childFunction;

To:

return childFunction();

Douglas Crockford (Pioneer of JSON, among other things) has a whole article devoted to closures, and scoping in javascript, and it would be well worth it to check out his other articles on javascript.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download