Monday, November 23, 2009

Javascript Closure Demo with Sample example Code

<input type="button" id="button_01" value="Buton 01" />
<br>
<input type="button" id="button_02" value="Buton 02" />


<script>

//global variable
var g ;

function fun1( arg )
{
var s = arg; // s is local variable of function fun1()
// Anonymous function assign to global variable g
g = function ()
{
alert(s);
}
}



fun1(
"First");
g() ;
// alert("First");
//
Now g is assigned to button 01
document.getElementById("button_01").onclick = g;

fun1(
"Second");
// Now g is overwrittern
g() ;// alert("Second");
//
Now g is assigned to button 02
document.getElementById("button_02").onclick = g;

</script>

Clicking any button same code will used to execution, but the value is different due to Closure.

function somename(){ ... }, is function with name

function (){...}, Without name is anonymous function , we can assign this function to any variable like somename=function(){...}

using variable outside anonymous function like alert(s), where s is defined in function fun1() but out side anonymous function ,so using s is a Closure.




No comments:

Post a Comment