DekGenius.com
[ Team LiB ] Previous Section Next Section

4.3 Nesting Named Functions

NN 4, IE 4

4.3.1 Problem

You want to create a function that belongs to only one other function.

4.3.2 Solution

Starting with IE 4 and NN 4, you can nest a function inside another function according to the following syntax model:

function myFuncA( ) {
    // statements go here
    function.myFuncB( ) {
        // more statements go here
    }
}

In this construction, the nested function may be accessed only by statements in the outer function (but see the Discussion about Netscape 6 and later). Statements in the nested function have access to variables declared in the outer function, as well as to global variables. Statements in the outer function, however, do not have access to the inner function's variables.

4.3.3 Discussion

The basic idea behind nested functions is that you can encapsulate all activity related to the outer function by keeping subroutine functions private to the outer function. Because the nested function is not directly exposed to the global space, you can reuse the function name in the global space or for a nested function inside some other outer function.

Netscape 6 and later extends the environment for nested functions in a logical and convenient way: a nested function acts as a method of the outer function object. There are some interesting ramifications with the way this feature is implemented. Consider the following test function set:

function myFuncA( ) {
    var valueA = "A";
    myFuncB( );
    function myFuncB( ) {
        var valueB = "B";
        alert(valueB);
        alert(valueA);
    }
}

When you invoke myFuncA( ) from the global space, it invokes its nested function, which dutifully displays the values of the two variables that are defined in the outer and inner functions. IE behaves the same way, as expected. But in Netscape 6 or later, you can invoke the nested function from the global space by way of the outer function:

myFuncA.myFuncB( );

Because the outer function does not execute in this direct access to myFuncB, the valueA variable is not initialized with any value. When myFuncB( ) runs, it shows the value of valueB, but valueA comes back as undefined. Therefore, access to the outer function's variables is possible only when the inner function is invoked by the outer function.

4.3.4 See Also

Recipe 4.1 for a discussion of variable scope.

    [ Team LiB ] Previous Section Next Section