Functions

  • URL ревизии: Ядро_JavaScript_1.5_Спровчник/Functions
  • Заголовок ревизии: Functions
  • ID ревизии: 267010
  • Создано:
  • Автор: drygunin
  • Это текущая версия? Нет
  • комментировать 30 words added, 32 words removed

Содержание версии

 

Summary

Generally speaking, a function is a "subprogram" that can be called by code external (or internal in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the function body. Objects and values can be passed to a function, and the function can return an object or value.

In JavaScript, functions are first-class objects, i.e. they are objects and can be manipulated and passed around like just like any other object. Specifically, they are Function objects.

General

Каждая функция в JavaScript на самом деле является объектом типа Function. See Function for information on properties and methods of Function objects.

Чтобы вернуть значение, функция должна иметь оператор return, который определяет возвращаемое значение. Функция, не имеющая определённого возвращаемого значения, возвращает undefined.

Non-object parameters, e.g. strings, numbers and booleans, are passed to functions by value; the value is passed to the function where it is stored in a new variable. If the function changes the value of the variable, this change is not reflected globally or in the calling function. Object parameters, e.g. objects, arrays and regular expressions, are passed to functions by reference; if you pass an object as a parameter to a function and the function changes the object's properties, that change is visible outside the function, as shown in the following example:

 function myFunc(theObject) {
    theObject.brand = "Toyota";
 }
 
 var mycar = {brand: "Honda", model: "Accord", year: 1998};
 alert(mycar.brand); // shows 'Honda'
 myFunc(mycar);      // pass object mycar to the function
 alert(mycar.brand); // shows 'Toyota' as the brand property of
                     // mycar was changed by the function)

The this keyword does not refer to the currently executing function, so you must refer to Function objects by name, even within the function body. Alternatively, you can use the arguments.callee property.

Defining functions

There are three ways to define functions:

The function declaration (function statement)

There is a special syntax for declaring functions (see function statement for details):

function name([param[, param[, ... param]]]) {
   statements
}
name
The function name.
param
The name of an argument to be passed to the function. A function can have up to 255 arguments.
statements
The statements comprising the body of the function.

The function expression (function operator)

A function expression is similar to and has the same syntax as a function declaration (see function operator for details):

function [name]([param] [, param] [..., param]) {
   statements
}
name
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
param
The name of an argument to be passed to the function. A function can have up to 255 arguments.
statements
The statements which comprise the body of the function.

The Function constructor

As all other objects, Function objects can be created using the new statement:

new Function ([arg1[, arg2[, ... argN]],] functionBody)
arg1, arg2, ... argN
Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript identifier or a list of such strings separated with a comma; for example "x", "theValue", or "a,b".
functionBody
A string containing the JavaScript statements comprising the function definition.

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

The arguments object

You can refer to a function's arguments within the function by using the arguments object. See arguments.

Scope and the function stack

some section about scope and functions calling other functions

Recursion

A function can refer to and call itself. There are three ways for a function to refer to itself:

  1. the function's name
  2. arguments.callee
  3. an in-scope variable that refers to the function

For example, consider the following function definition:

var foo = function bar() {
   // statements go here
};

Within the function body, the following are all equivalent:

  1. bar()
  2. arguments.callee()
  3. foo()

A function that calls itself is called a recursive function. In some ways, recursion is analogous to a loop. Both execute the same code multiple times, and both require a condition (to avoid an infinite loop, or rather, infinite recursion in this case). For example, the following loop:

var x = 0;
while (x < 10) { // "x < 10" is the loop condition
   // do stuff
   x++;
}

can be converted into a recursive function and a call to that function:

function loop(x) {
   if (x >= 10) // "x >= 10" is the exit condition (equivalent to "!(x < 10)")
      return;
   // do stuff
   loop(x + 1); // the recursive call
}
loop(0);

However, some algorithms cannot be simple iterative loops. For example, getting all the nodes of a tree structure (e.g. the DOM) is more easily done using recursion:

function walkTree(node) {
   if (node == null) // 
      return;
   // do something with node
   for (var i = 0; i < node.childNodes.length; i++) {
      walkTree(node.childNodes[i]);
   }
}

Compared to the function loop, each recursive call itself makes many recursive calls here.

It is possible to convert any recursive algorithm to a non-recursive one, but often the logic is much more complex and doing so requires the use of a stack. In fact, recursion itself uses a stack: the function stack.

The stack-like behavior can be seen in the following example:

function foo(i) {
   if (i < 0)
      return;
   document.writeln('begin:' + i);
   foo(i - 1);
   document.writeln('end:' + i);
}
foo(3);

which outputs:

begin:3
begin:2
begin:1
begin:0
end:0
end:1
end:2
end:3

Nested functions and closures

You can nest a function within a function. The nested (inner) function is private to its containing (outer) function. It also forms a closure.

A closure is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).

Since a nested function is a closure, this means that a nested function can "inherit" the arguments and variables of its containing function. In other words, the inner function contains the scope of the outer function.

To summarize:

  • The inner function can be accessed only from statements in the outer function.
  • The inner function forms a closure: the inner function can use the arguments and variables of the outer function, while 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

Since the inner function forms a closure, 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

Efficiency considerations

Notice how x is preserved when inside is returned. A closure preserves the arguments and variables in all scopes it contains. Since each call provides potentially different arguments, a closure must be created for each call to the outer function. In other words, each call to outside creates a closure. For this reason, closures can use up a lot of memory. The memory can be freed only when the returned inside is no longer accessible. In this case, the closure of inside is stored in result. Since result is in the global scope, the closure will remain until the script is unloaded (in a browser, this would happen when the page containing the script is closed).

Because of this inefficiency, avoid closures whenever possible, i.e. avoid nesting functions whenever possible. For example, consider the following example:

function assignOnclick(element) {
   element.onclick = function() {
      this.style.backgroundColor = 'blue';
   };
}

This can be rewritten to avoid the closure. However, the anonymous inner function would need to be named and would no longer be private to assignOnclick:

function assignOnclick(element) {
   element.onclick = element_onclick;
}

function element_onclick() {
   this.style.backgroundColor = 'blue';
}

Multiply-nested functions

Functions can be multiply-nested, i.e. a function (A) containing a function (B) containing a function (C). Both functions B and C form closures here, so B can access A and C can access B. In addition, since C can access B which can access A, C can also access A. Thus, the closures can contain multiple scopes; they recursively contain the scope of the functions containing it. This is called scope chaining. (Why it is called "chaining" will be explained later.)

Consider the following example:

function A(x) {
   function B(y) {
      function C(z) {
         alert(x + y + z);
      }
      C(3);
   }
   B(2);
}
A(1); // alerts 6 (1 + 2 + 3)

In this example, C accesses B's y and A's x. This can be done because:

  1. B forms a closure including A, i.e. B can access A's arguments and variables.
  2. C forms a closure including B.
  3. Because B's closure includes A, C's closure includes A, C can access both B and A's arguments and variables. In other words, C chains the scopes of B and A in that order.

The reverse, however, is not true. A cannot access C, because A cannot access any argument or variable of B, which C is a variable of. Thus, C remains private to only B.

Name conflicts

When two arguments or variables in the scopes of a closure have the same name, there is a name conflict. More inner scopes take precedence, so the inner-most scope takes the highest precedence, while the outer-most scope takes the lowest. This is the scope chain. The first on the chain is the inner-most scope, and the last is the outer-most scope. Consider the following:

function outside() {
   var x = 10;
   function inside(x) {
      return x;
   }
   return inside;
}
result = outside()(20); // returns 20 instead of 10

The name conflict happens at the statement return x and is between inside's parameter x and outside's variable x. The scope chain here is {inside, outside, global object}. Therefore inside's x takes precedences over outside's x, and 20 (inside's x) is returned instead of 10 (outside's x).

Function constructor vs. function declaration vs. function expression

Compare the following:

  1. a function defined with the Function constructor assigned to the variable multiply
    var multiply = new Function("x", "y", "return x * y;");
    
  2. a function declaration of a function named multiply
    function multiply(x, y) {
       return x * y;
    }
    
  3. a function expression of an anonymous function assigned to the variable multiply
    var multiply = function(x, y) {
       return x * y;
    }
    
  4. a function expression of a function named func_name assigned to the variable multiply
    var multiply = function func_name(x, y) {
       return x * y;
    }
    

All do approximately the same thing, with a few subtle differences:

  • There is a distinction between the function name and the variable the function is assigned to:
    • The function name cannot be changed, while the variable the function is assigned to can be reassigned.
    • The function name can be used only within the function's body. Attempting to use it outside the function's body results in an error (or undefined if the function name was previously declared via a var statement). For example:
      var y = function x() {};
      alert(x); // throws an error
      

      The function name also appears when the function is serialized via Function's toString method.

      On the other hand, the variable the function is assigned to is limited only by its scope, which is guaranteed to include the scope where the function is declared in.

    • As the 4th example shows, the function name can be different from the variable the function is assigned to. They have no relation to each other.
  • A function declaration also creates a variable with the same name as the function name. Thus, unlike those defined by function expressions, functions defined by function declarations can be accessed by their name in the scope they were defined in:
    function x() {}
    alert(x); // outputs x serialized into a string
    

    The following example shows how function names are not related to variables functions are assigned to. If a "function variable" is assigned to another value, it will still have the same function name:

    function foo() {}
    alert(foo); // alerted string contains function name "foo"
    var bar = foo;
    alert(bar); // alerted string still contains function name "foo"
    
  • A function defined by a Function does not have a function name. However, in the SpiderMonkey JavaScript engine, the serialized form of the function shows as if it has the name "anonymous". For example, alert(new Function()) outputs:
    function anonymous() {
    }
    

    Since the function actually does not have a name, anonymous is not a variable that can be accessed within the function. For example, the following would result in an error:

    var foo = new Function("alert(anonymous);");
    foo();
    
  • Unlike functions defined by function expressions or by the Function constructor, a function defined by a function declaration can be used before the function declaration itself. For example:
    foo(); // alerts FOO!
    function foo() {
       alert('FOO!');
    }
    
  • A function defined by a function expression inherits the current scope. That is, the function forms a closure. On the other hand, a function defined by a Function constructor does not inherit any scope other than the global scope (which all functions inherit).
  • Functions defined by function expressions and function declarations are parsed only once, while those defined by the Function constructor are not. That is, the function body string passed to the Function constructor must be parsed every time it is evaluated. Although a function expression creates a closure every time, the function body is not reparsed, so function expressions are still faster than "new Function(...)". Therefore the Function constructor should be avoided whenever possible.

A function declaration is very easily (and often unintentionally) turned into a function expression. A function declaration ceases to be one when it either:

  • becomes part of an expression
  • is no longer a "source element" of a function or the script itself. A "source element" is a non-nested statement in the script or a function body:
    var x = 0;               // source element
    if (x == 0) {            // source element
       x = 10;               // not a source element
       function boo() {}     // not a source element
    }
    function foo() {         // source element
       var y = 20;           // source element
       function bar() {}     // source element
       while (y == 10) {     // source element
          function blah() {} // not a source element
          y++;               // not a source element
       }
    }
    

Examples:

  • // function declaration
    function foo() {}
    
    // function expression
    (function bar() {})
    
    // function expression
    x = function hello() {}
    
  • if (x) {
       // function expression
       function world() {}
    }
    
  • // function statement
    function a() {
       // function statement
       function b() {}
       if (0) {
          // function expression
          function c() {}
       }
    }
    

Conditionally defining a function

Functions can be conditionally defined using function expressions or the Function constructor.

In the following script, the zero function is never defined and cannot be invoked, because 'if (0)' evaluates to false:

if (0)
   function zero() {
      document.writeln("This is zero.");
   }

If the script is changed so that the condition becomes 'if (1)', function zero is defined.

Note: Although this looks like a function declaration, this is actually a function expression since it is nested within another statement. See differences between function declarations and function expressions.

Note: Some JavaScript engines, not including SpiderMonkey, incorrectly treat any function expression with a name as a function declaration. This would lead to zero being defined, even with the always-false conditional. A safer way to define functions conditionally is to define the function anonymously and assign it to a variable:

if (0)
   var zero = function() {
      document.writeln("This is zero.");
   }

Functions as event handlers

In JavaScript, DOM event handlers are functions (as opposed to objects containing a handleEvent method in other DOM language bindings). The functions are passed an event object as the first and only parameter. Like any other parameter, if the event object does not need to be used, it can be omitted in the list of formal parameters.

Possible event targets in a HTML document include: window (Window objects, including frames), document (HTMLDocument objects), and elements (Element objects). In the HTML DOM, event targets have event handler properties. These properties are lowercased event names prefixed with "on", e.g. onfocus. An alternate and more robust way of adding event listeners is provided by DOM Level 2 Events.

Note: Events are part of the DOM, not of JavaScript. (JavaScript merely provides a binding to the DOM.)

The following example assigns a function to a window's "focus" event handler.

window.onfocus = function() {
   document.body.style.backgroundColor = 'white';
};

If a function is assigned to a variable, you can assign the variable to an event handler. The following code assigns a function to the variable setBGColor.

var setBGColor = new Function("document.body.style.backgroundColor = 'white';");

You can use this variable to assign a function to an event handler in several ways. Here are two such ways:

  1. scripting with DOM HTML event properties
    document.form1.colorButton.onclick = setBGColor;
    
  2. HTML event attribute
    <input name="colorButton" type="button"
       value="Change background color"
       onclick="setBGColor();"/>
    

    An event handler set this way is actually a function, named after the attribute, wrapped around the specified code. This is why the parenthesis in "setBGColor()" are needed here (rather than just "setBGColor"). It is equivalent to:

    document.form1.colorButton.onclick = function onclick(event) {
       setBGColor();
    };
    

    Note how the event object is passed to this anonymous function as parameter event. This allows the specified code to use the Event object:

    <input ...
        onclick="alert(event.target.tagName);"/>
    

Just like any other property that refers to a function, the event handler can act as a method, and this would refer to the element containing the event handler. In the following example, the function referred to by onfocus is called with this equal to window.

window.onfocus();

A common JavaScript novice mistake is appending parenthesis and/or parameters to the end of the variable, i.e. calling the event handler when assigning it. Adding those parenthesis will assign the value returned from calling the event handler, which is often undefined (if the function doesn't return anything), rather than the event handler itself:

document.form1.button1.onclick = setBGColor();

To pass parameters to an event handler, the handler must be wrapped into another function as follows:

document.form1.button1.onclick = function() {
   setBGColor('some value');
};

Backward compatibility

JavaScript 1.1 and earlier

You cannot nest a function statement in another statement or in itself.

Local variables within functions

arguments: An array-like object containing the arguments passed to the currently executing function.

arguments.callee: Specifies the currently executing function.

arguments.caller: Specifies the function that invoked the currently executing function.

arguments.length: Specifies the number of arguments passed to the function.

Examples

Example: Returning a formatted number

The following function returns a string containing the formatted representation of a number padded with leading zeros.

// This function returns a string padded with leading zeros
function padZeros(num, totalLen) {
   var numStr = num.toString();             // Initialize return value as string
   var numZeros = totalLen - numStr.length; // Calculate no. of zeros
   for (var i = 1; i <= numZeros; i++) {
      numStr = "0" + numStr;
   }
   return numStr;
}

The following statements call the padZeros function.

var result;
result = padZeros(42,4); // returns "0042"
result = padZeros(42,2); // returns "42"
result = padZeros(5,4);  // returns "0005" 

Example: Determining whether a function exists

You can determine whether a function exists by using the typeof operator. In the following example, a test is peformed to determine if the window object has a property called noFunc that is a function. If so, it is used; otherwise some other action is taken.

 if ('function' == typeof window.noFunc) {
   // use noFunc()
 } else {
   // do something else
 }

Note that in the if test, a reference to noFunc is used—there are no brackets "()" after the function name so the actual function is not called.

See also

Function, function statement, function operator

{{ NeedsTechnicalReview() }}

{{ languages( { "en": "en/Core_JavaScript_1.5_Reference/Functions", "ja": "ja/Core_JavaScript_1.5_Reference/Functions" } ) }}

Revision Source

<p> </p>
<h3 name="Summary">Summary</h3>
<p>Generally speaking, a function is a "subprogram" that can be <em>called</em> by code external (or internal in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the <em>function body</em>. Objects and values can be <em>passed</em> to a function, and the function can <em>return</em> an object or value.</p>
<p>In JavaScript, functions are first-class objects, i.e. they are objects and can be manipulated and passed around like just like any other object. Specifically, they are <code><a href="/ru/Core_JavaScript_1.5_Reference/Global_Objects/Function" title="ru/Core_JavaScript_1.5_Reference/Global_Objects/Function">Function</a></code> objects.</p>
<h3 name="General">General</h3>
<p>Каждая функция в JavaScript на самом деле является объектом типа <code>Function</code>. See <code><a href="/ru/Core_JavaScript_1.5_Reference/Global_Objects/Function" title="ru/Core_JavaScript_1.5_Reference/Global_Objects/Function">Function</a></code> for information on properties and methods of <code>Function</code> objects.</p>
<p>Чтобы вернуть значение, функция должна иметь оператор <code><a href="/ru/Core_JavaScript_1.5_Reference/Statements/return" title="ru/Core_JavaScript_1.5_Reference/Statements/return">return</a></code>, который определяет возвращаемое значение. Функция, не имеющая определённого возвращаемого значения, возвращает <code>undefined</code>.</p>
<p>Non-object parameters, e.g. strings, numbers and booleans, are passed to functions <em>by value</em>; the value is passed to the function where it is stored in a new variable. If the function changes the value of the variable, this change is not reflected globally or in the calling function. Object parameters, e.g. objects, arrays and regular expressions, are passed to functions <em>by reference</em>; if you pass an object as a parameter to a function and the function changes the object's properties, that change is visible outside the function, as shown in the following example:</p>
<pre> function myFunc(theObject) {
    theObject.brand = "Toyota";
 }
 
 var mycar = {brand: "Honda", model: "Accord", year: 1998};
 alert(mycar.brand); // shows 'Honda'
 myFunc(mycar);      // pass object mycar to the function
 alert(mycar.brand); // shows 'Toyota' as the brand property of
                     // mycar was changed by the function)
</pre>
<p>The <code>this</code> keyword does not refer to the currently executing function, so you must refer to <code>Function</code> objects by name, even within the function body. Alternatively, you can use the <a href="/ru/Core_JavaScript_1.5_Reference/Functions/arguments/callee" title="ru/Core_JavaScript_1.5_Reference/Functions/arguments/callee">arguments.callee</a> property.</p>
<h3 name="Defining_functions">Defining functions</h3>
<p>There are three ways to define functions:</p>
<h4 name="The_function_declaration_.28function_statement.29">The function declaration (<code>function</code> statement)</h4>
<p>There is a special syntax for declaring functions (see <a href="/ru/Core_JavaScript_1.5_Reference/Statements/function" title="ru/Core_JavaScript_1.5_Reference/Statements/function">function statement</a> for details):</p>
<pre class="eval">function <em>name</em>([<em>param</em>[, <em>param</em>[, ... <em>param</em>]]]) {
   <em>statements</em>
}
</pre>
<dl> <dt><code>name</code></dt> <dd>The function name.</dd>
</dl>
<dl> <dt><code>param</code></dt> <dd>The name of an argument to be passed to the function. A function can have up to 255 arguments.</dd>
</dl>
<dl> <dt><code>statements</code></dt> <dd>The statements comprising the body of the function.</dd>
</dl>
<h4 name="The_function_expression_.28function_operator.29">The function expression (<code>function</code> operator)</h4>
<p>A function expression is similar to and has the same syntax as a function declaration (see <a href="/ru/Core_JavaScript_1.5_Reference/Operators/Special_Operators/function_Operator" title="ru/Core_JavaScript_1.5_Reference/Operators/Special_Operators/function_Operator">function operator</a> for details):</p>
<pre class="eval">function [<em>name</em>]([<em>param</em>] [, <em>param</em>] [..., <em>param</em>]) {
   <em>statements</em>
}
</pre>
<dl> <dt><code>name</code></dt> <dd>The function name. Can be omitted, in which case the function becomes known as an anonymous function.</dd>
</dl>
<dl> <dt><code>param</code></dt> <dd>The name of an argument to be passed to the function. A function can have up to 255 arguments.</dd>
</dl>
<dl> <dt><code>statements</code></dt> <dd>The statements which comprise the body of the function.</dd>
</dl>
<h4 name="The_Function_constructor">The <code>Function</code> constructor</h4>
<p>As all other objects, <code>Function</code> objects can be created using the <code>new</code> statement:</p>
<pre class="eval">new Function ([<em>arg1</em>[, <em>arg2</em>[, ... <em>argN</em>]],] <em>functionBody</em>)
</pre>
<dl> <dt><code>arg1, arg2, ... arg<em>N</em></code></dt> <dd>Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript identifier or a list of such strings separated with a comma; for example "<code>x</code>", "<code>theValue</code>", or "<code>a,b</code>".</dd>
</dl>
<dl> <dt><code>functionBody</code></dt> <dd>A string containing the JavaScript statements comprising the function definition.</dd>
</dl>
<p>Invoking the <code>Function</code> constructor as a function (without using the <code>new</code> operator) has the same effect as invoking it as a constructor.</p>
<h3 name="The_arguments_object">The <code>arguments</code> object</h3>
<p>You can refer to a function's arguments within the function by using the <code>arguments</code> object. See <a href="/ru/Core_JavaScript_1.5_Reference/Functions/arguments" title="ru/Core_JavaScript_1.5_Reference/Functions/arguments">arguments</a>.</p>
<h3 name="Scope_and_the_function_stack">Scope and the function stack</h3>
<p><span class="comment">some section about scope and functions calling other functions</span></p>
<h3 name="Recursion">Recursion</h3>
<p>A function can refer to and call itself. There are three ways for a function to refer to itself:</p>
<ol> <li>the function's name</li> <li><code><a href="/ru/Core_JavaScript_1.5_Reference/Functions/arguments/callee" title="ru/Core_JavaScript_1.5_Reference/Functions/arguments/callee">arguments.callee</a></code></li> <li>an in-scope variable that refers to the function</li>
</ol>
<p>For example, consider the following function definition:</p>
<pre class="eval">var foo = function bar() {
   // statements go here
};
</pre>
<p>Within the function body, the following are all equivalent:</p>
<ol> <li><code>bar()</code></li> <li><code>arguments.callee()</code></li> <li><code>foo()</code></li>
</ol>
<p>A function that calls itself is called a <em>recursive function</em>. In some ways, recursion is analogous to a loop. Both execute the same code multiple times, and both require a condition (to avoid an infinite loop, or rather, infinite recursion in this case). For example, the following loop:</p>
<pre class="eval">var x = 0;
while (x &lt; 10) { // "x &lt; 10" is the loop condition
   // do stuff
   x++;
}
</pre>
<p>can be converted into a recursive function and a call to that function:</p>
<pre class="eval">function loop(x) {
   if (x &gt;= 10) // "x &gt;= 10" is the exit condition (equivalent to "!(x &lt; 10)")
      return;
   // do stuff
   loop(x + 1); // the recursive call
}
loop(0);
</pre>
<p>However, some algorithms cannot be simple iterative loops. For example, getting all the nodes of a tree structure (e.g. the <a href="/ru/DOM" title="ru/DOM">DOM</a>) is more easily done using recursion:</p>
<pre class="eval">function walkTree(node) {
   if (node == null) // 
      return;
   // do something with node
   for (var i = 0; i &lt; node.childNodes.length; i++) {
      walkTree(node.childNodes[i]);
   }
}
</pre>
<p>Compared to the function <code>loop</code>, each recursive call itself makes many recursive calls here.</p>
<p>It is possible to convert any recursive algorithm to a non-recursive one, but often the logic is much more complex and doing so requires the use of a stack. In fact, recursion itself uses a stack: the function stack.</p>
<p>The stack-like behavior can be seen in the following example:</p>
<pre class="eval">function foo(i) {
   if (i &lt; 0)
      return;
   document.writeln('begin:' + i);
   foo(i - 1);
   document.writeln('end:' + i);
}
foo(3);
</pre>
<p>which outputs:</p>
<pre class="eval">begin:3
begin:2
begin:1
begin:0
end:0
end:1
end:2
end:3
</pre>
<h3 name="Nested_functions_and_closures">Nested functions and closures</h3>
<p>You can nest a function within a function. The nested (inner) function is private to its containing (outer) function. It also forms a <em>closure</em>.</p>
<dl> <dd>A closure is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression). <a class="external" href="http://jibbering.com/faq/faq_notes/closures.html"></a></dd>
</dl>
<p>Since a nested function is a closure, this means that a nested function can "inherit" the arguments and variables of its containing function. In other words, the inner function contains the scope of the outer function.</p>
<p>To summarize:</p>
<ul> <li>The inner function can be accessed only from statements in the outer function.</li>
</ul>
<ul> <li>The inner function forms a closure: the inner function can use the arguments and variables of the outer function, while the outer function cannot use the arguments and variables of the inner function.</li>
</ul>
<p>The following example shows nested functions:</p>
<pre class="eval">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
</pre>
<p>Since the inner function forms a closure, you can call the outer function and specify arguments for both the outer and inner function:</p>
<pre class="eval">function outside(x) {
   function inside(y) {
      return x + y;
   }
   return inside;
}
result = outside(3)(5); // returns 8
</pre>
<h4 name="Efficiency_considerations">Efficiency considerations</h4>
<p>Notice how <code>x</code> is preserved when <code>inside</code> is returned. A closure preserves the arguments and variables in all scopes it contains. Since each call provides potentially different arguments, a closure must be created for each call to the outer function. In other words, each call to <code>outside</code> creates a closure. For this reason, closures can use up a lot of memory. The memory can be freed only when the returned <code>inside</code> is no longer accessible. In this case, the closure of <code>inside</code> is stored in <code>result</code>. Since <code>result</code> is in the global scope, the closure will remain until the script is unloaded (in a browser, this would happen when the page containing the script is closed).</p>
<p>Because of this inefficiency, avoid closures whenever possible, i.e. avoid nesting functions whenever possible. For example, consider the following example:</p>
<pre class="eval">function assignOnclick(element) {
   element.onclick = function() {
      this.style.backgroundColor = 'blue';
   };
}
</pre>
<p>This can be rewritten to avoid the closure. However, the anonymous inner function would need to be named and would no longer be private to <code>assignOnclick</code>:</p>
<pre class="eval">function assignOnclick(element) {
   element.onclick = element_onclick;
}

function element_onclick() {
   this.style.backgroundColor = 'blue';
}
</pre>
<h4 name="Multiply-nested_functions">Multiply-nested functions</h4>
<p>Functions can be multiply-nested, i.e. a function (A) containing a function (B) containing a function (C). Both functions B and C form closures here, so B can access A and C can access B. In addition, since C can access B which can access A, C can also access A. Thus, the closures can contain multiple scopes; they recursively contain the scope of the functions containing it. This is called <em>scope chaining</em>. (Why it is called "chaining" will be explained later.)</p>
<p>Consider the following example:</p>
<pre class="eval">function A(x) {
   function B(y) {
      function C(z) {
         alert(x + y + z);
      }
      C(3);
   }
   B(2);
}
A(1); // alerts 6 (1 + 2 + 3)
</pre>
<p>In this example, <code>C</code> accesses <code>B</code>'s <code>y</code> and <code>A</code>'s <code>x</code>. This can be done because:</p>
<ol> <li><code>B</code> forms a closure including <code>A</code>, i.e. <code>B</code> can access <code>A</code>'s arguments and variables.</li> <li><code>C</code> forms a closure including <code>B</code>.</li> <li>Because <code>B</code>'s closure includes <code>A</code>, <code>C</code>'s closure includes <code>A</code>, <code>C</code> can access both <code>B</code> <em>and</em> <code>A</code>'s arguments and variables. In other words, <code>C</code> <em>chains</em> the scopes of <code>B</code> and <code>A</code> in that order.</li>
</ol>
<p>The reverse, however, is not true. <code>A</code> cannot access <code>C</code>, because <code>A</code> cannot access any argument or variable of <code>B</code>, which <code>C</code> is a variable of. Thus, <code>C</code> remains private to only <code>B</code>.</p>
<h4 name="Name_conflicts">Name conflicts</h4>
<p>When two arguments or variables in the scopes of a closure have the same name, there is a <em>name conflict</em>. More inner scopes take precedence, so the inner-most scope takes the highest precedence, while the outer-most scope takes the lowest. This is the scope chain. The first on the chain is the inner-most scope, and the last is the outer-most scope. Consider the following:</p>
<pre class="eval">function outside() {
   var x = 10;
   function inside(x) {
      return x;
   }
   return inside;
}
result = outside()(20); // returns 20 instead of 10
</pre>
<p>The name conflict happens at the statement <code>return x</code> and is between <code>inside</code>'s parameter <code>x</code> and <code>outside</code>'s variable <code>x</code>. The scope chain here is {<code>inside</code>, <code>outside</code>, global object}. Therefore <code>inside</code>'s <code>x</code> takes precedences over <code>outside</code>'s <code>x</code>, and 20 (<code>inside</code>'s <code>x</code>) is returned instead of 10 (<code>outside</code>'s <code>x</code>).</p>
<h3 name="Function_constructor_vs._function_declaration_vs._function_expression"><code>Function</code> constructor vs. function declaration vs. function expression</h3>
<p>Compare the following:</p>
<ol> <li>a function defined with the <code>Function</code> constructor assigned to the variable <code>multiply</code> <pre>var multiply = new Function("x", "y", "return x * y;");
</pre> </li> <li>a <em>function declaration</em> of a function named <code>multiply</code> <pre>function multiply(x, y) {
   return x * y;
}
</pre> </li> <li>a <em>function expression</em> of an anonymous function assigned to the variable <code>multiply</code> <pre>var multiply = function(x, y) {
   return x * y;
}
</pre> </li> <li>a function expression of a function named <code>func_name</code> assigned to the variable <code>multiply</code> <pre>var multiply = function func_name(x, y) {
   return x * y;
}
</pre> </li>
</ol>
<p>All do approximately the same thing, with a few subtle differences:</p>
<ul> <li>There is a distinction between the function name and the variable the function is assigned to: <ul> <li>The function name cannot be changed, while the variable the function is assigned to can be reassigned.</li> <li>The function name can be used only within the function's body. Attempting to use it outside the function's body results in an error (or <code>undefined</code> if the function name was previously declared via a <code>var</code> statement). For example: <pre>var y = function x() {};
alert(x); // throws an error
</pre> <p>The function name also appears when the function is serialized via <a href="/ru/Core_JavaScript_1.5_Reference/Global_Objects/Function/toString" title="ru/Core_JavaScript_1.5_Reference/Global_Objects/Function/toString"><code>Function</code>'s toString method</a>.</p> <p>On the other hand, the variable the function is assigned to is limited only by its scope, which is guaranteed to include the scope where the function is declared in.</p> </li> <li>As the 4th example shows, the function name can be different from the variable the function is assigned to. They have no relation to each other.</li> </ul> </li> <li>A function declaration also creates a variable with the same name as the function name. Thus, unlike those defined by function expressions, functions defined by function declarations can be accessed by their name in the scope they were defined in: <pre>function x() {}
alert(x); // outputs x serialized into a string
</pre> <p>The following example shows how function names are not related to variables functions are assigned to. If a "function variable" is assigned to another value, it will still have the same function name:</p> <pre>function foo() {}
alert(foo); // alerted string contains function name "foo"
var bar = foo;
alert(bar); // alerted string still contains function name "foo"
</pre> </li> <li>A function defined by a <code>Function</code> does not have a function name. However, in the <a href="/ru/SpiderMonkey" title="ru/SpiderMonkey">SpiderMonkey</a> JavaScript engine, the serialized form of the function shows as if it has the name "anonymous". For example, <code>alert(new Function())</code> outputs: <pre>function anonymous() {
}
</pre> <p>Since the function actually does not have a name, <code>anonymous</code> is not a variable that can be accessed within the function. For example, the following would result in an error:</p> <pre>var foo = new Function("alert(anonymous);");
foo();
</pre> </li> <li>Unlike functions defined by function expressions or by the <code>Function</code> constructor, a function defined by a function declaration can be used before the function declaration itself. For example: <pre>foo(); // alerts FOO!
function foo() {
   alert('FOO!');
}
</pre> </li> <li>A function defined by a function expression inherits the current scope. That is, the function forms a closure. On the other hand, a function defined by a <code>Function</code> constructor does not inherit any scope other than the global scope (which all functions inherit).</li> <li>Functions defined by function expressions and function declarations are parsed only once, while those defined by the <code>Function</code> constructor are not. That is, the function body string passed to the <code>Function</code> constructor must be parsed every time it is evaluated. Although a function expression creates a closure every time, the function body is not reparsed, so function expressions are still faster than "<code>new Function(...)</code>". Therefore the <code>Function</code> constructor should be avoided whenever possible.</li>
</ul>
<p>A function declaration is very easily (and often unintentionally) turned into a function expression. A function declaration ceases to be one when it either:</p>
<ul> <li>becomes part of an expression</li> <li>is no longer a "source element" of a function or the script itself. A "source element" is a non-nested statement in the script or a function body: <pre>var x = 0;               // source element
if (x == 0) {            // source element
   x = 10;               // not a source element
   function boo() {}     // not a source element
}
function foo() {         // source element
   var y = 20;           // source element
   function bar() {}     // source element
   while (y == 10) {     // source element
      function blah() {} // not a source element
      y++;               // not a source element
   }
}
</pre> </li>
</ul>
<p>Examples:</p>
<ul> <li> <pre>// function declaration
function foo() {}

// function expression
(function bar() {})

// function expression
x = function hello() {}
</pre> </li> <li> <pre>if (x) {
   // function expression
   function world() {}
}
</pre> </li> <li> <pre>// function statement
function a() {
   // function statement
   function b() {}
   if (0) {
      // function expression
      function c() {}
   }
}
</pre> </li>
</ul>
<h4 name="Conditionally_defining_a_function">Conditionally defining a function</h4>
<p>Functions can be conditionally defined using function expressions or the <code>Function</code> constructor.</p>
<p>In the following script, the <code>zero</code> function is never defined and cannot be invoked, because '<code>if (0)</code>' evaluates to false:</p>
<pre class="eval">if (0)
   function zero() {
      document.writeln("This is zero.");
   }
</pre>
<p>If the script is changed so that the condition becomes '<code>if (1)</code>', function <code>zero</code> is defined.</p>
<p>Note: Although this looks like a function declaration, this is actually a function expression since it is nested within another statement. See <a href="#Function_constructor_vs._function_declaration_vs._function_expression">differences between function declarations and function expressions</a>.</p>
<p>Note: Some JavaScript engines, not including <a href="/ru/SpiderMonkey" title="ru/SpiderMonkey">SpiderMonkey</a>, incorrectly treat any function expression with a name as a function declaration. This would lead to <code>zero</code> being defined, even with the always-false conditional. A safer way to define functions conditionally is to define the function anonymously and assign it to a variable:</p>
<pre class="eval">if (0)
   var zero = function() {
      document.writeln("This is zero.");
   }
</pre>
<h3 name="Functions_as_event_handlers">Functions as event handlers</h3>
<p>In JavaScript, <a href="/ru/DOM" title="ru/DOM">DOM</a> event handlers are functions (as opposed to objects containing a <code>handleEvent</code> method in other DOM language bindings). The functions are passed an <a href="/ru/DOM/event" title="ru/DOM/event">event</a> object as the first and only parameter. Like any other parameter, if the event object does not need to be used, it can be omitted in the list of formal parameters.</p>
<p>Possible event targets in a <a href="/ru/HTML" title="ru/HTML">HTML</a> document include: <code>window</code> (<code>Window</code> objects, including frames), <code>document</code> (<code>HTMLDocument</code> objects), and elements (<code>Element</code> objects). In the <a class="external" href="http://www.w3.org/TR/DOM-Level-2-HTML/">HTML DOM</a>, event targets have event handler properties. These properties are lowercased event names prefixed with "on", e.g. <code>onfocus</code>. An alternate and more robust way of adding event listeners is provided by <a class="external" href="http://www.w3.org/TR/DOM-Level-2-Events/">DOM Level 2 Events</a>.</p>
<p>Note: Events are part of the DOM, not of JavaScript. (JavaScript merely provides a binding to the DOM.)</p>
<p>The following example assigns a function to a window's "focus" event handler.</p>
<pre>window.onfocus = function() {
   document.body.style.backgroundColor = 'white';
};
</pre>
<p>If a function is assigned to a variable, you can assign the variable to an event handler. The following code assigns a function to the variable <code>setBGColor</code>.</p>
<pre>var setBGColor = new Function("document.body.style.backgroundColor = 'white';");
</pre>
<p>You can use this variable to assign a function to an event handler in several ways. Here are two such ways:</p>
<ol> <li>scripting with DOM HTML event properties <pre>document.form1.colorButton.onclick = setBGColor;
</pre> </li> <li>HTML event attribute <pre>&lt;input name="colorButton" type="button"
   value="Change background color"
   onclick="setBGColor();"/&gt;
</pre> <p>An event handler set this way is actually a function, named after the attribute, wrapped around the specified code. This is why the parenthesis in "<code>setBGColor()</code>" are needed here (rather than just "<code>setBGColor</code>"). It is equivalent to:</p> <pre>document.form1.colorButton.onclick = function onclick(event) {
   setBGColor();
};
</pre> <p>Note how the event object is passed to this anonymous function as parameter <code>event</code>. This allows the specified code to use the Event object:</p> <pre>&lt;input ...
    onclick="alert(event.target.tagName);"/&gt;
</pre> </li>
</ol>
<p>Just like any other property that refers to a function, the event handler can act as a method, and <code>this</code> would refer to the element containing the event handler. In the following example, the function referred to by <code>onfocus</code> is called with <code>this</code> equal to <code>window</code>.</p>
<pre class="eval">window.onfocus();
</pre>
<p>A common JavaScript novice mistake is appending parenthesis and/or parameters to the end of the variable, i.e. calling the event handler when assigning it. Adding those parenthesis will assign the <em>value returned from calling the event handler</em>, which is often <code>undefined</code> (if the function doesn't return anything), rather than the event handler itself:</p>
<pre class="eval">document.form1.button1.onclick = setBGColor();
</pre>
<p>To pass parameters to an event handler, the handler must be wrapped into another function as follows:</p>
<pre class="eval">document.form1.button1.onclick = function() {
   setBGColor('some value');
};
</pre>
<h3 name="Backward_compatibility">Backward compatibility</h3>
<h4 name="JavaScript_1.1_and_earlier">JavaScript 1.1 and earlier</h4>
<p>You cannot nest a function statement in another statement or in itself.</p>
<h3 name="Local_variables_within_functions">Local variables within functions</h3>
<p><a href="/ru/Core_JavaScript_1.5_Reference/Functions/arguments" title="ru/Core_JavaScript_1.5_Reference/Functions/arguments">arguments</a>: An array-like object containing the arguments passed to the currently executing function.</p>
<p><a href="/ru/Core_JavaScript_1.5_Reference/Functions/arguments/callee" title="ru/Core_JavaScript_1.5_Reference/Functions/arguments/callee">arguments.callee</a>: Specifies the currently executing function.</p>
<p><a href="/ru/Core_JavaScript_1.5_Reference/Functions/arguments/caller" title="ru/Core_JavaScript_1.5_Reference/Functions/arguments/caller">arguments.caller</a>: Specifies the function that invoked the currently executing function.</p>
<p><a href="/ru/Core_JavaScript_1.5_Reference/Functions/arguments/length" title="ru/Core_JavaScript_1.5_Reference/Functions/arguments/length">arguments.length</a>: Specifies the number of arguments passed to the function.</p>
<h3 name="Examples">Examples</h3>
<h4 name="Example:_Returning_a_formatted_number">Example: Returning a formatted number</h4>
<p>The following function returns a string containing the formatted representation of a number padded with leading zeros.</p>
<pre class="eval">// This function returns a string padded with leading zeros
function padZeros(num, totalLen) {
   var numStr = num.toString();             // Initialize return value as string
   var numZeros = totalLen - numStr.length; // Calculate no. of zeros
   for (var i = 1; i &lt;= numZeros; i++) {
      numStr = "0" + numStr;
   }
   return numStr;
}
</pre>
<p>The following statements call the padZeros function.</p>
<pre class="eval">var result;
result = padZeros(42,4); // returns "0042"
result = padZeros(42,2); // returns "42"
result = padZeros(5,4);  // returns "0005" 
</pre>
<h4 name="Example:_Determining_whether_a_function_exists">Example: Determining whether a function exists</h4>
<p>You can determine whether a function exists by using the <code>typeof</code> operator. In the following example, a test is peformed to determine if the <code>window</code> object has a property called <code>noFunc</code> that is a function. If so, it is used; otherwise some other action is taken.</p>
<pre> if ('function' == typeof window.noFunc) {
   // use noFunc()
 } else {
   // do something else
 }
</pre>
<p>Note that in the <code>if</code> test, a reference to <code>noFunc</code> is used—there are no brackets "()" after the function name so the actual function is not called.</p>
<h3 name="See_also">See also</h3>
<p><a href="/ru/Core_JavaScript_1.5_Reference/Global_Objects/Function" title="ru/Core_JavaScript_1.5_Reference/Global_Objects/Function">Function</a>, <a href="/ru/Core_JavaScript_1.5_Reference/Statements/function" title="ru/Core_JavaScript_1.5_Reference/Statements/function">function statement</a>, <a href="/ru/Core_JavaScript_1.5_Reference/Operators/Special_Operators/function_Operator" title="ru/Core_JavaScript_1.5_Reference/Operators/Special_Operators/function_Operator">function operator</a></p>
<p>{{ NeedsTechnicalReview() }}</p>
<p>{{ languages( { "en": "en/Core_JavaScript_1.5_Reference/Functions", "ja": "ja/Core_JavaScript_1.5_Reference/Functions" } ) }}</p>
Вернуть эту версию