O'Reilly logo

Learning JavaScript by Shelley Powers

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 result. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required