Javascript closures

Closure is when a function “remembers” its lexical scope even when the function is executed outside that lexical scope.

Closure is the capability for an function to remember ac access of its lexical scope even when that function is executed outside of that defined lexical scope.

 

function foo(){

var bar =”bar”;

 

function baz(){

console.log(bar);

}

bam(baz);

}

 

function bam(baz){

baz(); // displays bar

}

 

foo();

// the capability of bar to continue to reference that same scope lookup even bar is executing outside is called closure

What is lexical scope??

Console.log(bar) will look for “bar” inside the baz function, then it move on to function foo and access the bar value over line 2. This is called lexical scope.

Another Example:

Lets say, on each time you click a button.. value has to be increment. In generally first procedure will show you on clicking each time same value will be printing..where are second procedure shows you a closure method.

 

1st procedure:

function count(){

var a=5;

a=a+1;

}

When you assign this count() method to ng-click like ng-click=”count()” will always return 6.

The desired functionality like each click count should increase can be achieved by closures as follows:

var count = (function(){

var a=5;

return function(){

a = a+1;

return a;

}

});

 

count(); // return 6

count(); // this time return 7

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s