Sunday, March 18, 2007

Javascript Nesting functions

You can nest a function within a function. The nested (inner) function is private to its containing (outer) function:

The inner function can be accessed only from statements in the outer function.

The inner function can use the arguments and variables of the outer function. The outer function cannot use the arguments and variables of the inner function.
The following example shows nested functions:
function addSquares (a,b) {
function square(x) {
return x*x
return square(a) + square(b)
a=addSquares(2,3) // returns 13
b=addSquares(3,4) // returns 25
c=addSquares(4,5) // returns 41

When a function contains a nested function, you can call the outer function and specify arguments for both the outer and inner function:

function outside(x) {
function inside(y) {
return x+y
return inside
result=outside(3)(5) // returns 8

No comments :