Javascript Closures

closure is an inner function that has access to the outer (enclosing) function's variables—scope chain. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function's variables, and it has access to the global variables

<script type="text/javascript">

var str = "var a;a=11;var b=4;";
eval(str);

function fun() {
document.getElementById("btn").onclick=function (){
//alert(a);
//alert(add());
//alert(e1.name);
emp.prototype.country = null;
e1.country = "india";
alert(e1.country);
}
}


var add = (function() {
var x=10;
//return x++;
return function(){return x++;}
})();

function emp(name,age) {
this.name=name;
this.age=age;
}

var e1 = new emp("firos",20);

var testfun = (function() {
var x = 10;
x++;
alert("this is testfun"+x);

return function(){
x++;
alert("inner"+x);
return function() {
x++;
alert("inner mosr"+x);
}
}
})()();


</script>


<body onload="">

<input type="button" id="btn" value="click me" onclick="testfun()"  />

</body>
</html>

Comments