3.6. Close on Closures

When discussing the prototype object, it is necessary to consider JavaScript closures. The prototype is used to extend the definition of an object, regardless of what other scope is in effect. The prototype is available as a characteristic of the type, regardless of whether you have an instance of the object. The prototype is independent from the state during which it was created. Closures, on the other hand, are used to leverage the scope in play at the time the closure is created. A closure refers to the way you can define an inner function to take advantage of the state of the outer function's context and make it visible externally so it can execute after the outer function has returned. The behavior of the closure can depend on the state and scope that existed when the closure was created. Scoping behavior is the same in JavaScript as it is in C# and Visual Basic, with one notable exception (as shown in Figure 3-1 at the beginning of the chapter): Using a variable without declaring it gives it a global scope.

If you search for information on closures, you are bound to find some hard-to-follow, overly complex scientific explanations. Concrete specific examples are generally better at explaining closures than formal definitions. The prototype can reference properties and functions using the this operator, but the lexical scoping means that any outside variables that happen to exist do not come into play. It is typically an error when you try to use transient ...

Get Professional ASP.NET 3.5 AJAX now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.