Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
Function Literal Function objects are created with function literals: // Create a variable called add and store a function // in it that adds two numbers. var add = function (a, b) { return a + b; }; A function literal has four parts. The first part is the reserved word function . The optional second part is the function's name. The function can use its name to call itself recursively. The name can also be used by debuggers and development tools to identify the function. If a function is not given a name, as shown in the previ- ous example, it is said to be anonymous. The third part is the set of parameters of the function, wrapped in parentheses. Within the parentheses is a set of zero or more parameter names, separated by com- mas. These names will be defined as variables in the function. Unlike ordinary vari- ables, instead of being initialized to undefined , they will be initialized to the arguments supplied when the function is invoked. The fourth part is a set of statements wrapped in curly braces. These statements are the body of the function. They are executed when the function is invoked. A function literal can appear anywhere that an expression can appear. Functions can be defined inside of other functions. An inner function of course has access to its parameters and variables. An inner function also enjoys access to the parameters and variables of the functions it is nested within. The function object created by a func- tion literal contains a link to that outer context. This is called closure. This is the source of enormous expressive power. Invocation Invoking a function suspends the execution of the current function, passing control and parameters to the new function. In addition to the declared parameters, every function receives two additional parameters: this and arguments . The this parame- ter is very important in object oriented programming, and its value is determined by the invocation pattern. There are four patterns of invocation in JavaScript: the method invocation pattern, the function invocation pattern, the constructor invoca- tion pattern, and the apply invocation pattern. The patterns differ in how the bonus parameter this is initialized. Invocation | 27