Lexical scoping (Definition)

The scope within which functions are executed.

Functions are lexically scoped in JavaScript and because they are not dynamically scoped, they are static to within the location they are defined. This means they run in the global scope of the document in which they live and not the one they are called from.

In versions of JavaScript prior to 1.2, the scope for a function declaration was limited to the global scope. This was a simple scope arrangement and caused little confusion and difficulty. From version 1.2 onwards, because functions can now be defined inside functions, they cannot be called from outside those functions and the scoping rules start to become more complex.

There becomes an issue of persistence of the scope of a function and if a nested function is called from outside its containing function, the containing function's scope is still present and added to the scope chain along the way when the inner function is called.

To illustrate this, suppose a function AAA is created and within it, another BBB is created.

You can call AAA and while executing its code, a call to BBB might be made. Inside BBB, the scope chain contains the global object, the call object of AAA and the call object of BBB. If BBB is called from outside AAA, as in AAA.BBB(), then the exact same scope chain is constructed.

This can become even more complex if function objects are manufactured at run-time. It might be possible to conceive a function object factory that can preserve the scope chain that persisted at the time the functions were created. If those function objects are preserved and executed later, the scope chain that was in existence at the time they were created will be restored when they are executed. This is far too confusing to be of great use and may turn out to be somewhat non-portable.

This capability is realized by storing the function that has been manufactured in a special kind of object. These are called Closure objects and are implemented visibly in Navigator 4.

See also:__parent__, Closure object