Jul 2, 2007


Closures are means through which inner functions can refer to the variables present in their outer enclosing function after their parent functions have already terminated.

            function delayedAlert(msg, time)
            }, time);

            delayedAlert("Welcom!", 2000);

Curring is a way to to, essentially, prefill in a number of arguments to a function, creating a new, simpler function. Closure can create such currying functionality.

            function addGenerator(num)
            //return a simple function for adding two
            //numbers with first number barrowed from the generator
            return function(toAdd){
            return number + toAdd

            var addFive = addGenerator(5);
            add(addFive(4) == 9);


There's another, common, javascript coding problem that closures can solve. New javascript developers tend to accidentally leave a lot of extra variable sitting in the global scope. This is generally considered to be bad practice, as those extra variable could quietly interfere with other libraries, causing confusing problem to occur. Using a self-executing, anonymous function you can essentially hide all normally globally variables from being seen by other code.

            //The variable that would, normally, be global
            var msg = "Thanks for visiting!";

            //binding a new function to a global object
            window.onunload = function(){

            })(); //close off the anonymous function and execute it


Remember that closures allow you to reference variables that exist within the parent function. However, it does not provide the value of the variable at the time it is created. It provides the last value of the variable with in the parent function. The most common issue under which you'ill see this occur is during a for loop. This is one variable being

            // An element with an ID of main
            var obj = document.getElementById("main");

            // An array of items to bind to
            var items = [ "click", "keypress" ];

            // Iterate through each of the items

            for ( var i = 0; i < items.length; i++ )
            // Use a self-executed anonymous function to induce scope
            // Remember the value within this scope
            var item = items[i];
            // Bind a function to the elment
            obj[ "on" + item ] = function() {
            // item refers to a parent variable that has been successfully
            // scoped within the context of this for loop
            alert( "Thanks for your " + item );};

No comments:

Post a Comment