현재 번역은 완벽하지 않습니다. 한국어로 문서 번역에 동참해주세요.
일반적으로, 함수 (function) 는 함수 밖의 (혹은 재귀 호출의 경우 함수 안의) 코드가 호출하는 "부프로그램" (subprogram) 이다. 프로그램 그 자체와 비슷하게, 함수는 함수 본문 (function body) 이라고 부르는 문장의 연속으로 구성된다. 함수에 값을 전달할 수 있고, 함수는 값을 반환 (return) 할 수 있다.
JavaScript에서 함수는 일급 객체 (first-class object) 이고, 그 말은, 함수는 객체이고, 다른 객체들과 똑같이 다루거나 전달할 수 있다는 것이다. 좀 더 상세하게 말하자면, 함수는 Function
객체이다.
좀 더 자세한 설명과 예제를 보려면, JavaScript 함수 안내서를 보라.
설명
JavaScript의 모든 함수는 Function
객체이다. Function
객체의 속성 (property) 과 메소드의 정보를 보려면 Function
을 보라.
함수는 프로시저 (procedure) 와는 다르다. 함수는 항상 값을 반환하지만, 프로시저는 값을 반환할 수도 있고, 어떠한 값도 반환하지 않을수도 있다.
기본값 외의 특정한 값을 반환하려면, 함수는 반드시 반환할 값을 지정하는 return
구문을 가져야 한다. return 구문이 없는 함수는 기본값을 반환할 것이다. new 지정어 (keyword) 로 호출하는 생성자 (constructor)
의 예에서, 기본값은 새로 만들어진 객체의 this
매개변수 (parameter) 이다. 다른 모든 함수들의 경우, 기본 반환값은 undefined
이다.
함수를 호출할때 전달해주는 매개변수들은 함수의 인자 (argument) 라고 한다. 인자는 함수에 값 복사로 전달된다 (by value). 만약 함수가 인자의 값을 변경한다고 해도, 이러한 변경은 이 함수를 호출한 호출자나 전역 범위로 반영되지 않는다. 하지만, 객체 참조도 역시 하나의 값이지만, 특이한 모습을 보인다. 만약 함수가 참조하는 객체의 속성을 바꿔버린다면, 그 변경은 함수 밖에서도 보일 것이다. 예제를 보라.
/* 'myFunc' 함수 정의 */ function myFunc(theObject) { theObject.brand = "Toyota"; } /* * 'mycar' 변수 정의 : * 새로운 객체를 만들어 초기화하고, * 'mycar' 라는 변수에 만든 객체의 참조를 할당 */ var mycar = { brand: "Honda", model: "Accord", year: 1998 }; /* 'Honda' 가 콘솔에 출력함 */ console.log(mycar.brand); /* 객체의 참조를 함수에 전달 */ myFunc(mycar); /* * 객체에 있는 'brand' 속성의 'Toyota'를 콘솔에 출력함. * 함수에 의해 값이 바뀌었으므로 'Honda'가 아닌 'Toyota'를 출력함 */ console.log(mycar.brand);
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.
Defining functions
There are several 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
expression)
A function expression is similar to and has the same syntax as a function declaration (see function expression 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 generator function declaration (function*
statement)
Note: Generator function are an experimental technology, part of the ECMAScript 6 proposal, and are not widely supported by browsers yet.
There is a special syntax for declaration generator 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 generator function expression (function*
expression)
Note: Generator function are an experimental technology, part of the ECMAScript 6 proposal, and are not widely supported by browsers yet.
A generator function expression is similar to and has the same syntax as a generator function declaration (see function* expression
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 arrow function expression (=>)
Note: Arrow function expressions are an experimental technology, part of the ECMAScript 6 proposal, and are not widely supported by browsers yet.
An arrow function expression has a shorter syntax and lexically binds its this value (see arrow functions for details):
([param] [, param]) => { statements } param => expression
param
- The name of an argument. Zero arguments need to be indicated with
()
. For only one argument the parentheses are not required. (likefoo => 1
) statements or expression
- Multiple statements need to be enclosed in brackets. A single expression requires no brackets. The expression is also the implicit return value of that function.
The Function
constructor
Note: Using the Function
constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.
As all other objects, Function
objects can be created using the new
operator:
new Function (arg1, arg2, ... argN, functionBody)
arg1, arg2, ... argN
- Zero or more names to be used by the function as formal argument names. Each must be a string that conforms to the rules for 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 GeneratorFunction
constructor
Note: Arrow function expressions are an experimental technology, part of the ECMAScript 6 proposal, and are not widely supported by browsers yet.
Note: GeneratorFunction
is not a global object, but could be obtained from generator function instance (see GeneratorFunction
for more detail).
Note: Using the GeneratorFunction
constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.
As all other objects, GeneratorFunction
objects can be created using the new
operator:
new GeneratorFunction (arg1, arg2, ... argN, functionBody)
arg1, arg2, ... argN
- Zero or more names to be used by the function as formal argument names. Each must be a string that conforms to the rules for 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.
Function parameters
Note: Default and rest parameters are experimental technology, part of the ECMAScript 6 proposal, and are not widely supported by browsers yet.
Default parameters
Default function parameters allow formal parameters to be initialized with default values if no value or undefined
is passed. For more details, see default parameters.
Rest parameters
The rest parameter syntax allows to represent an indefinite number of arguments as an array. For more details, see rest parameters.
The arguments
object
You can refer to a function's arguments within the function by using the arguments
object. See arguments.
arguments
: An array-like object containing the arguments passed to the currently executing function.arguments.callee
: The currently executing function.arguments.caller
: The function that invoked the currently executing function.arguments.length
: The number of arguments passed to the function.
Defining method functions
Getter and setter functions
You can define getters (accessor methods) and setters (mutator methods) on any standard built-in object or user-defined object that supports the addition of new properties. The syntax for defining getters and setters uses the object literal syntax.
- get
-
Binds an object property to a function that will be called when that property is looked up.
- set
- Binds an object property to a function to be called when there is an attempt to set that property.
Method definition syntax
Note: Method definitions are experimental technology, part of the ECMAScript 6 proposal, and are not widely supported by browsers yet.
Starting with ECMAScript 6, you are able to define own methods in a shorter syntax, similar to the getters and setters. See method definitions for more information.
var obj = { foo() {}, bar() {} };
Function
constructor vs. function declaration vs. function expression
Compare the following:
A function defined with the Function
constructor assigned to the variable multiply:
function multiply(x, y) { return x * y; }
A function expression of an anonymous function assigned to the variable multiply:
var multiply = function(x, y) { return x * y; };
A function expression of a function named func_name
assigned to the variable multiply:
var multiply = function func_name(x, y) { return x * y; };
Differences
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:
A function defined by 'new 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 each and every time the constructor is called. 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 generally be avoided whenever possible.
It should be noted, however, that function expressions and function declarations nested within the function generated by parsing a Function constructor
's string aren't parsed repeatedly. For example:
var foo = (new Function("var bar = \'FOO!\';\nreturn(function() {\n\talert(bar);\n});"))(); foo(); // The segment "function() {\n\talert(bar);\n}" of the function body string is not re-parsed.
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 declaration function a() { // function declaration function b() {} if (0) { // function expression function c() {} } }
Conditionally defining a function
Functions can be conditionally defined using either //function statements// (an allowed extension to the ECMA-262 Edition 3 standard) or the Function
constructor. Please note that such function statements are no longer allowed in ES5 strict. Additionally, this feature does not work consistently cross-browser, so you should not rely on it.
In the following script, the zero
function is never defined and cannot be invoked, because 'if (0)
' evaluates its condition 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 kind of function looks like a function declaration, it is actually an expression (or statement), 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 definition. This would lead to zero
being defined, even with the always-false if
condition. 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."); } }
Examples
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"
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.
Specifications
Specification | Status | Comment |
---|---|---|
ECMAScript 1st Edition (ECMA-262) | Standard | Initial definition. Implemented in JavaScript 1.0 |
ECMAScript 5.1 (ECMA-262) The definition of 'Function Definition' in that specification. |
Standard | |
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Function definitions' in that specification. |
Standard | New: Arrow functions, Generator functions, default parameters, rest parameters |
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'function*' in that specification. |
Standard | Initial definition. |
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Arrow Function Definitions' in that specification. |
Standard | Initial definition. |
Browser compatibility
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
Generator function | 39 | 26.0 (26.0) | ? | 26 | ? |
Arrow function | Not supported | 22.0 (22.0) | Not supported | Not supported | Not supported |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
Generator function | ? | 39 | 26.0 (26.0) | ? | 26 | ? |
Arrow function | Not supported | Not supported | 22.0 (22.0) | Not supported | Not supported | Not supported |