Nested Functions, Function Closure, and Memory Leaks

Tip

Again, this is fairly advanced JavaScript programming, but because it occurs quite frequently in Ajax programming, I felt it best to include in the book. However, as with recursion, you may want to finish the book and then return to this section.

Another interesting aspect of function literals in JavaScript is their use as nested functions. Consider the following:

function outer (args) {
   function inner (args) {
      inner statements;
   }
}

With a nested function, the inner function operates within the scope of the outer function, including having access to the outer function’s variables and arguments. The outer function, though, does not have access to the inner function’s variables, nor does the calling application have access to the inner function. (Well, not unless it’s created as a function literal and returned to the calling application, which then adds its own complication.)

Example 5-6 demonstrates creating a nested, inner-function literal, which is then returned to the calling application. The inner function uses the outer function’s one argument, as well as its one variable. When the inner function is returned to the calling application and invoked directly, it concatenates the string passed as a parameter to the original outer-function call to the string passed to it directly as an argument. The inner function concatenates this string with that created as the local variable in the outer function, and then returns the ...

Get Learning JavaScript 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.