top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Quick Introduction To Immediately Invoked Function Expressions & Closures

+4 votes
231 views

Modern web applications heavily rely on JavaScript and JavaScript frameworks. That's why ASP.NET developers need to be aware of JavaScript concepts such as Immediately Invoked Function Expressions (IIFE) and Closures. To that end this article presents a quick introduction to these two features.

Immediately Invoked Function Expressions (IIFE)

An immediately invoked function expression is a JavaScript function that is executed immediately after it is created. Usually you create a named or anonymous JavaScript function and then somewhere in the code you call that function. Consider the following code:

function HelloWorld() {
    alert("Hello World!");
}

var myfunction = function () {
    alert("Hello World!");
}

HelloWorld();
myfunction();

Here, the code creates a named function called HelloWorld(). The code also creates an anonymous function and stores it in a variable - myfunction. The code then proceeds to call these two functions. That means function creation and function execution are two distinct steps.

Using IIFE you can create and run a function immediately. The following syntax shows how:

(function () {
    alert("Hello World!");
})();

As you can see, the above code creates an anonymous function. The whole function is enclosed in brackets and is immediately followed by (). This way function creation and execution are combined. The function can take parameters just like any other JavaScript function.

(function (msg) {
    alert(msg);
})("Hello World!");

Now the function takes msg parameter. While invoking the function a value of Hello World! is passed to the function.

If you ever created a jQuery plugin you will find that many of them use IIFE pattern. Consider the following jQuery plugin:

(function ($) {
    $.fn.myPlugin = function (settings) {
       //plugin code here
    }
})(jQuery);

As you can see, this template for a jQuery plugin consists of an anonymous function that takes a single parameter - $ ($ is a valid variable name in JavaScript). The actual code of the plugin goes inside the inner anonymous function (the one that is assigned to myPlugin ).

The outer function is immediately executed by passing jQuery object to it as a parameter. This way all the inner code of the IIFE refers to the jQuery object as $. This pattern ensures that the meaning of $ is preserved for all the inside code.

JavaScript Closures

 Simply put a closure is an inner function that has access to the parameters and variables defined in the outer function. Moreover, this environment is preserved even if the outer function returns.

The following code will make this clear:

function Outer(msg) {

    function Inner() {
        alert(msg);
    }

    Inner();
}

Outer("Hello World!");

Here, the outer function accepts msg parameter. The msg parameter is used by the inner function and is displayed using an alert. Then the outer function calls the inner function. The external code then invokes the outer function (external code won't have access to inner function).

Now let's see a bit complex usage of closures.

function Outer() {
    var msg = "";

    var obj = {};
    obj.setMsg = function (val) {
        msg = val;
    };
    obj.getMsg = function () {
        return msg;
    };

    return obj;
}

var result = Outer();
result.setMsg("Hello World!");
alert(result.getMsg());

Here, the Outer() function defines a variable - msg - in it's private scope. Then a JavaScript object is created and two function properties are added to it - setMsg() and getMsg(). The setMsg() function assigns a new value to the msg variable. The getMsg() returns the value of msg to the caller.

The obj is returned to the caller. At this stage the Outer() returns. Since Outer() has returned, ordinarily you would expect msg variable to go out of scope. However, result.setMsg() and result.getMsg() still work as expected. This indicates that even if the function has returned the environment has been preserved.

Closures are widely used in jQuery as well as AngularJS to organize the code.

posted Nov 10, 2016 by Shivaranjini

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button


Related Articles

If you are keeping yourself updated with the latest in the .NET sphere, you are probably aware that Microsoft has provided an inbuilt support for jQuery in Visual Studio 2010. Though it was possible to use jQuery with ASP.NET even before VS 2010, formally including jQuery as a part of website created using VS2010 means that more and more developers are going to learn and use it. If you haven't tried jQuery yet this article series will teach you everything needed to master jQuery and use it in ASP.NET applications.

What is jQuery?

The official website for jQuery defines jQuery as follows:

"jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript."

Let's try to understand this description of jQuery in a bit detail.

jQuery is a JavaScript library

As a ASP.NET developer you must have used JavaScript in one way or the other. The standard JavaScript no doubt helps you code rich and responsive web pages but the amount of code that you need to write is often too much. For example, if you wish to write a fancy popup menu from ground up using JavaScript it might be a time consuming task. To simplify such development and make you more productive several JavaScript libraries are available and jQuery is one of them. There are others such as Mootools, Prototype and Dojo. The fact that Microsoft is supporting jQuery in its products and investing resources into it clearly indicates its popularity. As you would expect jQuery is cross-browser and supports all leading browsers including IE 6+, FF 2+, Chrome, Safari 3+ and Opera 9+.

jQuery is fast and concise

jQuery is highly optimized library. Moreover it is compact. The production version of jQuery 1.4.3 is just 26 KB and development version 179 KB. This compactness means less data to be downloaded at client side without compromising stunning UI effects.

Scope of jQuery

jQuery simplifies HTML DOM navigation considerably. For example, document.getElementById("Text1") becomes just $("#Text1"). Simple. Isn't it? Most of the JavaScript functionality goes in client side event handlers. jQuery is handy when it comes to event handling. If you are thinking about your AJAX functionality don't worry. jQuery allows you to make AJAX calls to ASP.NET Web Services, WCF services or even page methods. If needed jQuery can be used along with ASP.NET AJAX.

jQuery is designed to change the way that you write JavaScript

That's true! jQuery dramatically changes the way you write JavaScript code. Initially you may find syntax of jQuery bit odd but once you get hang of it you will probably never look at any other library (or at least to the traditional way of writing JavaScript). For example, a common JavaScript file contains too many small to huge functions and you keep calling them individually whenever required. With jQuery the "chain" of operations makes your code compact and handy. 

Ok. Enough of introduction. Now, let's complete the "hello world" ritual :-) In next section you will build a simple ASP.NET webform with some server controls on it that perform a trivial job of displaying "Hello world".

Download jQuery

Before you start any development with jQuery you need to download its latest version. You can do so by visiting http://jquery.com and then downloading "Development" version. If you are using VS2010 then you need not download anything because when you create a new website by default jQuery library is already added for you (see screenshot below)

image

In the above screenshot jquery-1.4.1.js is the development version, jquery-1.4.1.min.js is minified production version and jquery-1.4.1-vsdoc.js is the VS2010 IntelliSense file that enables IntelliSense for jQuery (see below).

image

In the remainder of this article I will be using VS2008. If you are using VS2010 then just cleanup the default website by removing master page and other unwanted stuff.

Design a simple web form

Create a new website in VS2008 and create a new folder named Scripts. Copy the downloaded jQuery file in the Scripts folder. Though you can place it anywhere inside your website it is recommended to keep all JavaScript files under one folder typically named Scripts. The default name for the jQuery file is jquery-1.4.3.js but you can change it to something else if you so wish.

Now open the default web form and add a <script> tag in its <head> section as shown below :

<script src="Scripts/jquery-1.4.3.js" type="text/javascript"></script>

Now place a TextBox and a Button web control on the web form. Switch back to HTML source view and add another <script> block as shown below:

<script type="text/javascript">

$(document).ready(OnPageReady);

function OnPageReady() 
{
  $("#Button1").click(OnButtonClick)
}

function OnButtonClick(event) 
{
  alert("Hello world from jQuery!");
  event.preventDefault();
}
</script>

The first line is where jQuery magic starts. The $ sign is a shortcut to base object jQuery. So, $(...) is actually same as jQuery(...). If you ever coded in ASP.NET AJAX this concept should be familiar to you. The ready() is an event that fires when the wen page under consideration is fully loaded and its various elements are ready to be accessed. The event handler for ready event is supplied in the parenthesis as OnPageReady. OnPageReady() is a normal JavaScript function that wires an event handler for the client side click event of the button. It does so again by using $ shortcut. This time, however, ID of the button control is specified prefixing it with #. The click is an event and you specify its handler as OnButtonClick. The event handler receives an event object giving more information about the event. The OnButtonClick() is another function that simply displays "Hello World from jQuery!" using JavaScript alert. The OnButtonClick function also calls event.preventDefault() method so as to prevent web form postback that normally would have happened due to Button web server control.

Ok. If you run the web form you should see something like this :

image

Easy! Isn't it?

Now let's modify the above code as shown below:

$(document).ready(
 function() {
   $("#Button1").click(function(event) {
    alert("Hello world from jQuery!");
    event.preventDefault();
   }
  )
 }
)

This is a compact version of the code that achieves the same functionality. Here, instead of defining separate functions you have written all the code there itself. You may compare this code with anonymous methods of C#.

Adding something more...

Now that the "Hello world" ritual is over let's add some extra features to our code. Begin by defining the following CSS class in your web form:

    <style type="text/css">
        .NoFocus
        {
            background-color:White;
            border:solid 1px gray;
        }

        .Focus
        {
            background-color:silver;
            border:solid 3px gray;
        }

    </style>

The CSS class NoFocus will be applied to the textbox when it doesn't have focus whereas CSS class Focus will be applied when the textbox receives the focus. To accomplish this change the preceding code (compact version) as shown below:

        $(document).ready
        (
            function() 
            {
                $("#Button1").click(
                function(event) 
                {
                    alert($("#TextBox1").val());
                    return false;
                }
                )
                
                ,
                $("#TextBox1").addClass("NoFocus")
                ,
                $("#TextBox1").focus(
                function(event)
                {
                   $("#TextBox1").removeClass("NoFocus");
                   $("#TextBox1").addClass("Focus");
                }
                ),
                
                $("#TextBox1").blur(
                function(event)
                {
                   $("#TextBox1").removeClass("Focus");
                   $("#TextBox1").addClass("NoFocus");
                }
                )
            }
        )

Notice the lines marked in bold letters. The click event handler of the button now displays whatever has been entered in the textbox. To retrieve textbox value you use val() method. Initially the textbox won't have focus and its CSS class should be NoFocus. This is done using addClass() method. The focus() and blur() event handlers simply add and remove the appropriate classes using addClass() and removeClass() methods respectively.

The following figure shows a sample run of the web page with the modified code. 

image

That's all for this part. In the next part you will learn about jQuery Selectors and how to use their power while selecting certain elements from a web page.

READ MORE

Ajax stands for "Asynchronous JavaScript and XML".

JavaScript includes features of sending asynchronous http request using XMLHttpRequest object. Ajax is about using this ability of JavaScript to send asynchronous http request and get the xml data as a response (also in other formats) and update the part of a web page (using JavaScript) without reloading or refreshing entire web page.

The following figure illustrates the Ajax functionality.

Ajax

The jQuery library includes various methods to send Ajax requests. These methods internally use XMLHttpRequest object of JavaScript. The following table lists all the Ajax methods of jQuery.

jQuery Ajax MethodsDescription
ajax()Sends asynchronous http request to the server.
get()Sends http GET request to load the data from the server.
Post()Sends http POST request to submit or load the data to the server.
getJSON()Sends http GET request to load JSON encoded data from the server.
getScript()Sends http GET request to load the JavaScript file from the server and then executes it.
load()Sends http request to load the html or text content from the server and add them to DOM element(s).

The jQuery library also includes following events which will be fired based on the state of the Ajax request.

jQuery Ajax EventsDescription
ajaxComplete()Register a handler function to be called when Ajax requests complete.
ajaxError()Register a handler function to be called when Ajax requests complete with an error.
ajaxSend()Register a handler function to be called before Ajax request is sent.
ajaxStart()Register a handler function to be called when the first Ajax request begins.
ajaxStop()Register a handler function to be called when all the Ajax requests have completed.
ajaxSuccess()Register a handler function to be called when Ajax request completes successfully.

Advantages of jQuery Ajax:

  1. Cross-browser support
  2. Simple methods to use
  3. Ability to send GET and POST requests
  4. Ability to Load JSON, XML, HTML or Scripts

Let's look at an overview of important jQuery Ajax methods in the next section.

READ MORE
...