JavaScript Closures are considered advanced material, reserved for the gurus of matter. Much has been written about them, but especially in academia, with little or no attempt made to make the subject understandable to the non-academic. That's really a shame, because the closures are the answer to the problem of how to bind variables to functions that are called at a later time. Today's article will explain what the closures are summarized some common dilemmas and ways that these closures can be used to overcome them.
Closure occurs when a function creates an environment that binds local variables to it so that to stay alive after the function has returned. The closure is a special type of object that combines two things: a function, and local variables that were in scope at the time that created the closure. In the following example, getNameFunction () is a closure that incorporates both the getName () and "Rob" string that is local to the scope of the external function. When running the code, it shows an alert box that says "Hi Rob!". A second alert shows that the variable is now displayName getName () function without the variable name. Finally, a third warning is educated through a setTimeout () and confirms that the name is still in the memory, long after the initial call to getNameFunction ():
- function getNameFunction()
- {
- var name = "Rob";
- return function getName()
- {
- return name;
- }
- }
- var displayName = function()
- {
- var getName = getNameFunction();
- alert( "Hello " + getName() + "!" );
- return getName;
- }();
- //holds the getName() function
- alert(displayName);
- //call it again later...
- setTimeout( 'alert( "Your name is " + displayName() )', 10 );
0 comments:
Post a Comment