Home arrow JavaScript arrow Page 4 - Variables, Functions, and Flow Control
JAVASCRIPT

Variables, Functions, and Flow Control


This two-part series offers a mix of JavaScript tricks to help you with your everyday projects. It is excerpted from chapter 4 of the JavaScript & DHTML Cookbook, Second Edition, written by Danny Goodman (O'Reilly, 2008; ISBN: 0596514085). Copyright © 2008 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

Author Info:
By: O'Reilly Media
Rating: 5 stars5 stars5 stars5 stars5 stars / 3
December 11, 2009
TABLE OF CONTENTS:
  1. · Variables, Functions, and Flow Control
  2. · 4.2 Creating a Named Function
  3. · 4.3 Nesting Named Functions
  4. · 4.4 Creating an Anonymous Function

print this article
SEARCH DEVARTICLES

TOOLS YOU CAN USE

advertisement
Variables, Functions, and Flow Control - 4.4 Creating an Anonymous Function
(Page 4 of 4 )

Problem

You 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.

Solution

You can use an alternative 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();

Discussion

Anonymous 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.

Assigning anonymous function definitions to object properties--thus creating object methods--is a good way to remove groups of related functions from the global scope. In large projects containing multiple libraries or frameworks (often from multiple authoring sources), unintentionally redundant function names can cause havoc. See Recipe 3.14 for suggestions on minimizing such conflicts.

See Also

Recipe 4.3 for creating traditional named functions; Recipe 3.14 for using anonymous functions to reduce global naming conflicts.

Please check back Monday for the conclusion to this article.


DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

blog comments powered by Disqus
JAVASCRIPT ARTICLES

- More Top jQuery Tutorials for Beginners
- More Top jQuery Plugins for Menus
- Top jQuery Tutorials for Beginners
- New UI Framework and SDK for JavaScript Rele...
- JavaScript OpenPGP Tool, Node.js 0.6.3 Avail...
- Yahoo Releases Cocktails Language and Develo...
- Customizing jQuery Slideshows: Dynamic Contr...
- Customizing jQuery Slideshows: the animate()...
- Customizing jQuery Slideshows: slideUp() and...
- Customizing jQuery Slideshows: hide() and sh...
- Web Workers: Performing Calculations in Para...
- More Top JavaScript Frameworks and Libraries
- More Dynamic jQuery Styling Techniques
- The Top JavaScript Libraries
- The Top JavaScript Frameworks

Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 



© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 11 - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials