Java Script: Closure

Closure:

Closure is -when a function remember it’s lexical scope even when function is executing outside that defined lexical scope.

Closure is kind of hidden reference or say live link to the scope object.

In JavaScript closures are created every time a function is created, at function creation time.

Closure bundles the lexical environment, a closure gives access to an outer function’s scope from an inner function.

To use a closure define a function inside another function and expose it. To expose a function, return it or pass it to another function. The inner function will have access to the variables in the outer function scope, even after the outer function has returned.

Example:

function foo(){

var bar = “bar”;

return function(){

alert(bar);

};

}

 

function bam () {

foo()();    //Result: bar

}

 

 

bam();
**Var me = this;
For example basically the  above statement utilizes closure in JavaScript. It is used to carry the particular instance of this to function calls where this has a different meaning.

**When in a outer function closure have multiple shared scopes i.e two or more inner functions, it will not get garbage collected until all references goes away.

 

** Putting IIFE inside a loop can create a closure on it to have value persist till end.

for (var i = 1; i <= 5; i++) {

(function(i){

setTimeout(function(){

console.log(“i: “+ i);

}, i*1000);

   })(i);

}

Closure common use:

# Closure are commonly used to give objects data privacy( i.e. program to an interface, not an implementation). The enclosed variables are only in scope within the containing outer function.

 

# Event handler: Able to return to environment.

function foo(){

var ba = “bar”;

$(“#btn”).click(function(evt){

alert(bar);

});

}

foo();

 

# Callback Functions: 

 

# Closure can also be used to create stateful functions whose return values may be influenced by their internal state.

 

# In functional Programming, closures are frequently used for partial application and currying.

 

Partial applied function that takes a function with multiple parameters and returns a function with fewer function.

 


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s