[ Team LiB ] |
4.4 Creating an Anonymous FunctionNN 4, IE 4 4.4.1 ProblemYou want to define a function in the form of an expression that you can, for example, pass as a parameter to an object constructor or assign to an object's method. 4.4.2 SolutionYou can use an alternate syntax for defining functions without creating an explicitly named function (as shown in Recipe 4.2). Called an anonymous function, this syntax has all the components of a function definition except its identifier. The syntax model is as follows: var someReference = function( ) {statements go here}; Statements inside the curly braces are semicolon-delimited JavaScript statements. You can define parameter variables if they're needed: var someReference = function(paramVar1[,..., paramVarN]) {statements go here}; Invoke the function via the reference to the function: someReference( ); 4.4.3 DiscussionAnonymous function creation returns an object of type function. Therefore, you can assign the right side of the statement to any assignment statement where a function reference (the function name without parentheses) is expected. To demonstrate, we'll make a version of a shortcut object constructor from Recipe 3.8. It starts with an ordinary function definition that gets invoked as a method of four objects defined with shortcut syntax: function showAll( ) { alert("Employee " + this.name + " is " + this.age + " years old."); } var employeeDB = [{name:"Alice", age:23, show:showAll}, {name:"Fred", age:32, show:showAll}, {name:"Jean", age:28, show:showAll}, {name:"Steve", age:24, show:showAll}]; Notice how in the object constructors, a reference to the showAll( ) function is assigned to the show method name. Invoking this method from one of the objects is done in the following manner: employeeDB[2].show( ); For the sake of example, we assign an anonymous function to the first object. The anonymous function is custom-tailored for the first object and replaces the reference to showAll( ): var employeeDB = [{name:"Alice", age:23, show :function( ) {alert("Alice\'s age is not open to the public.")}}, {name:"Fred", age:32, show:showAll}, {name:"Jean", age:28, show:showAll}, {name:"Steve", age:24, show:showAll}]; Now, if you invoke employeeDB[0].show( ), the special alert displays itself because the anonymous function is running instead of the showAll( ) function. We have saved the need to create an external function with its own identifier just to act as an intermediary between the show method name and the statements to execute when the method is invoked. 4.4.4 See AlsoRecipe 4.2 for creating traditional named functions. |
[ Team LiB ] |