OpenSource For You

Closures in Javascript

-

function greet(){ var name = “sandya”; function greet_by_name() {

alert (“hello “+ name);

} }

greet_by_name();

In the above code snippet, there is an inner function greet_by_name, whLFh Ls GHfinHG LnsLGH an ouWHr function greet. The variable name inside the inner function will match the variable name GHfinHG Ln WhH closest enclosing scope—which, in this case, is the variable name GHfinHG Ln WhH ouWHr IunFWLon, greet. Therefore, we can print the name as ‘sandya’ in the inner function greet_by_name. Now let us consider a sOLJhW PoGLfiFaWL­on Wo WhH aboYH FoGH: function greet(){ var name = “sandya”; return function greet_by_name() {

alert (“hello “+ name);

}; } //This is where the closure is created var greet_sandya = greet(); //the closure function is invoked greet_sandya();

If you run the above code, you will see the same output as before. However, note that we returned a function greet_ by_ name from the function greet. So when we executed the statement ‘ var greet_ sandya = greet();’, we only executed greet, and assigned the return value greet_ by_ name to the variable greet_ sandya. We did not actually execute the function greet_ by_ name.

When we executed greet_ sandya in the next line, we executed greet_ by_ name, since it had been assigned to the greet_ sandya variable earlier. Now, the question is: How is greet_ sandya able to access the variable name defined inside its outer function greet successful­ly, even though greet has already finished executing? Well, the answer lies in closures. A closure not only includes a function definition, but it also includes the environmen­t where the function was defined. This allows greet_ sandya to access the variables defined inside greet when it is actually executed. However, it is not all that simple. Since name is a local variable allocated on the stack of the greet function, how can it still be available when the function greet has already finished execution and is no longer active on the call stack? Well, that will be answered when we discuss closures in detail next month.

Newspapers in English

Newspapers from India