How to use anonymous functions and closures with Javascript

          

Anonymous functions and closures


Book Excerpt: Object-Oriented JavaScript

>What encapsulation, inheritance, and polymorphism mean
>How JavaScript functions work
>How to use anonymous functions and closures
>How to read a class diagram, and implement it using JavaScript
>How to work with JavaScript prototypes
>How the execution context and scope affect the output of JavaScript functions
>How to implement inheritance using closures and prototypes
>What JSON is, and what a JSON structure looks like
This chapter excerpt from Microsoft AJAX Library Essentials by Cristian Darie, Bogdan Brinzarea, is printed with permission from Packt Publishing, Copyright 2007.

Anonymous Functions

Anonymous functions can be created adhoc and used instead of a named function. Although this can hinder readability when the function is more complex, you can do this if you don't intend to reuse a function's code. In the following example we pass such an anonymous function to DisplayGreeting(), instead of passing GetCurrentHour():

// call DisplayGreeting
DisplayGreeting(
function()
{
      return (new Date()).getHours();
}
);

This syntax is sure to look strange if this is the first time you have worked with anonymous functions. You can compact it on a single line if it helps understanding it better:

DisplayGreeting( function() { return (new Date()).getHours(); } );

This code can be tested online at http://www.cristiandarie.ro/asp-ajax/ AnonymousFunction.html.

Inner Functions and JavaScript Closures

JavaScript functions implement the concept of closures, which are functions that are defi ned inside other functions, and use contextual data from the parent functions to execute. You can fi nd a complete and technically accurate defi nition of closures at http://en.wikipedia.org/wiki/Closure_(computer_science).

In JavaScript a function can be regarded as a named block of code that you can execute, but it can also be used as a data member inside another function, in which case it is referred to as an inner functions. In other words, a JavaScript function can contain other functions.

Say that we want to upgrade the initial ShowHelloWorld() function by separating the code that displays the greeting message into a separate function inside ShowHelloWorld(). This is a possible implementation, and the output continues to be the same as before:

// call function to display greeting message
ShowHelloWorld();
     // "Hello, World" function
     function ShowHelloWorld()
      {
         // declaring new variables
          var date = new Date();
          var hour = date.getHours();
          // call DisplayGreeting supplying the current hour as parameter
          DisplayGreeting(hour);

         // display greeting
      function DisplayGreeting(hour)
      {
           if (hour >= 22 || hour <= 5)
                document.write("Goodnight, world!");
          else
               document.write("Hello, world!");
     }
}

Here, we created a function named DisplayGreeting() inside ShowHelloWorld(), which displays a greeting message depending on the hour parameter it receives. The execution rules apply here as well. This new function needs to be called explicitly from its parent function in order to execute.

This code can be tested online at http://www.cristiandarie.ro/asp-ajax/JavaScriptClosure.html.

Related Links
>Object Oriented Programming Interview Questions

Concurrency with AOP

Concurrency is the system's ability to act with several requests simultaneously, such a way that threads don't corrupt the state of objects when they gain access at the same time............

OOPS in .NET

What is the relation between Classes and Objects? Explain different properties of Object Oriented Systems. What is difference between Association, Aggregation and Inheritance relationships? Explain the features of an abstract class in NET. Difference between abstract classes and interfaces Similarities and difference between Class and structure in .NET Features of Static/Shared classes. What is Operator Overloading in .NET?.............

What is object oriented programming (OOP)?

The object oriented programming is commonly known as OOP. Most of the languages are developed using OOP concept. Object-oriented programming (OOP) is a programming concept that uses "objects" to develop a system.........

What are the various elements of OOP?

Various elements of OOP are.........



Write your comment - Share Knowledge and Experience


Latest placement tests
Latest links
 
Latest MCQs
» General awareness - Banking » ASP.NET » PL/SQL » Mechanical Engineering
» IAS Prelims GS » Java » Programming Language » Electrical Engineering
» English » C++ » Software Engineering » Electronic Engineering
» Quantitative Aptitude » Oracle » English » Finance
Home | About us | Sitemap | Contact us | We are hiring