Categories:
Partners

A function within a function?

For a quick review, you may want to glance at JavaScript Kit's tutorial on Creating Custom Objects Via JavaScript. This page and the next build heavily on the concepts introduced there.
It's not a very well-known fact that you can create a function within a function.  You might think that would be a dumb idea -- why not just define the function normally, outside all functions, like this:

function outerF(x) { 
    return 3 * innerF(x) 
    } 

function innerF(x) { 
    return 4 * x 
    }

This is certainly a legitimate action.  But we are allowed to define inner functions, like this:

function outerF(x) { 
    function innerF(x) { 
        return 4 * x 
        } 
    return 3 * innerF(x) 
    } 

What makes this interesting is that the innerF() function is NOT defined outside the outerF() function:

function outerF(x) { 
    function innerF(x) { 
        return 4 * x 
        } 
    alert(innerF(4)) // alerts 16
    return 3 * innerF(x) 
    } 
alert(outerF(5)) // alerts 60
alert(innerF(4)) // throws an exception 

You can see this in action (the error is not canceled) by clicking on this sample link.

Right now, you might be thinking, Okay, so I can have one function inside another function, and there won't be a reference outside the function.  How do I use that inner function out in the real world? JavaScript Kit's objects tutorial gives us the clue, but I'll finish it off in the next page.

Copyright 1997-2014 JavaScript Kit. NO PART may be reproduced without author's permission.