Javascript Closures

September 16, 2008 at 2:10 pm | Posted in Javascript | Leave a comment
Tags:

One of the features of Javascript is closures , Javascript closures keep the local variables of a function even after it returns. That happens when a function is declared inside another function ,the local variables of the outer function will still exist even after the outer function returns.

function outer()
{
var name="mabdelghani";
var inner=function()
{
alert(name);
};
return inner;
}

var testFunction=outer();
alert(testFunction);
testFunction();

In the above code snippet , a function inner is defined inside another function outer , the local variable name is available even after function outer returns.

The result of the following line

alert(testFunction);

is
function()
{
alert(name);
}
and the result of the following line

testFunction();

is mabdelghani
Which means that the inner function which is referenced by testFunction doesn’t keep a copy of the name variable and it references the value of the local variable inside outer function though that function is returned.

It’s not necessary that the local variables in closures are to be declared before the inner function, They can be declared anywhere in the outer function before returning from it.

the following links are useful to know more about Javascript closures

http://www.jibbering.com/faq/faq_notes/closures.html

http://blog.morrisjohns.com/javascript_closures_for_dummies

About these ads

Leave a Comment »

RSS feed for comments on this post. TrackBack URI

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

Blog at WordPress.com. | The Pool Theme.
Entries and comments feeds.

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: