If you are a C/C++ programmer, then you are not used to nesting functions. In JavaScript, you can have one function inside another. In this three-part series, I answer the following questions: can you call a nested function from outside the outermost function? Can a nested function call an outer function? What is the scope within nested functions? I will also show you how to pass arguments between nested functions and look at the relationship between nested functions and the JavaScript object.
The example described above is similar to one person having a child, who then also has a child -- a grandparent, parent, and child. It's three people, all in one line. You have a function nesting within one function, which is also nesting within another function.
This is not the only way to have nested functions. Another way is to have a function with one or more functions immediately nested, and then each of these nested (inner) functions would have one or more functions immediately nested. This goes down until you end up with a tree-like structure.
We shall not look at the tree-like nested functions in this series. The JavaScript 1.5 reference does not say anything explicitly about the-tree like structure. We shall use the single line structure to explain most of the features in this series; wherever we need to have more than one function nested at the same level, I will indicate that to you.
In this part of the series we shall see how the functions can be called. In the next part of the series we shall look at the scope of arguments and variables within the functions. In the third and last part of the series, we shall see how we can use a set of nested functions in a JavaScript object type.
Example
This is the example we shall use to illustrate most of the principles. We shall be modifying the code as we go along.
function fnName1()
{
alert('Statements 1A')
function fnName2()
{
alert('Statements 2A')
function fnName3()
{
alert('Statements 3')
}
alert('Statements 2B')
}
alert('Statements 1B')
}
For simplicity, where the statements are to occur, I have just written an alert statement that displays a message indicating the nesting level of the statements. Please read through the function to appreciate what I have said.