Javascript
Closures
A closure can be defined as a JavaScript
feature in which the inner function has access to the outer function variable.
It has 3 Scope
- Access to its own scope.
- Access to the variables of the outer function.
- Access to the global variables.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<h2 style="background-color:
rgb(9, 238, 9);color:rgb(255, 0, 0);font-weight: bolder;font-family: Georgia,
'Times New Roman', Times, serif;">Closures</h2>
<h5 style="color:
rgb(231, 15, 166);">Output</h5>
<script>
function fun()
{
var a = 4;
// 'a' is the local
variable, created by the fun()
function innerfun() // the innerfun() is the inner function, or a closure
{
return a;
}
return innerfun;
}
var output = fun();
document.write(output());
document.write(" ");
document.write(output());
</script>
</head>
<body>
</body>
</html>
Output
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<h2 style="background-color:
rgb(9, 238, 9);color:rgb(255, 0, 0);font-weight: bolder;font-family: Georgia,
'Times New Roman', Times, serif;">Closures</h2>
<h5 style="color:
rgb(231, 15, 166);">Output</h5>
<script>
function fun(a)
{
function innerfun(b){
return a*b;
}
return innerfun;
}
var output = fun(4);
document.write(output(4));
document.write(" ");
document.write(output(5));
</script>
</head>
<body>
</body>
</html>
Output
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<h2 style="background-color:
rgb(9, 238, 9);color:rgb(255, 0, 0);font-weight: bolder;font-family: Georgia,
'Times New Roman', Times, serif;">Closures</h2>
<h5 style="color:
rgb(231, 15, 166);">Output</h5>
<script>
function fun()
{
function closure(val)
{
return function()
{
return val;
}
}
var a = [];
var i;
for (i
= 0; i < 5; i++)
{
a[i] = closure(i);
}
return a;
}
var output = fun();
document.write(output[0]());
document.write(" ");
document.write(output[1]());
document.write(" ");
document.write(output[2]());
document.write(" ");
document.write(output[3]());
document.write(" ");
document.write(output[4]());
</script>
</head>
<body>
</body>
</html>
Output
0 comments:
Post a Comment