Closure
The good news about scope is that inner functions get access to the parameters and
variables of the functions they are defined within (with the exception of this and arguments). This is a very good thing.
Our getElementsByAttribute function worked
because it declared a results variable, and the
inner function that it passed to walk_the_DOM
also had access to the results variable.
A more interesting case is when the inner function has a longer lifetime than its outer function.
Earlier, we made a myObject that had a value and an increment method. Suppose we wanted to protect the value from
unauthorized changes.
Instead of initializing myObject with an object
literal, we will initialize myObject by calling a
function that returns an object literal. That function defines a value variable. That variable is always available to
the increment and getValue methods, but the function's scope keeps it hidden from the
rest of the program:
var myObject = (function () {
var value = 0;
return {
increment: function (inc) {
value += typeof inc === 'number' ? inc : 1;
},
getValue: function ( ) {
return value;
}
};
}());We are not assigning a function to myObject. We
are assigning the result of invoking that function. Notice the ( ) on the last line. The function returns an object
containing two methods, and those methods continue to enjoy the privilege of access
to the value variable.
The Quo constructor from earlier in this
chapter produced an object with a status property
and a get_status method. ...