How Does Closure Work in Javascript?

时间:2024-11-03 20:04:56

Simply, closure is the scope that it can visite and operate the variables outside of the function when the function is created.

In another words, closure can visite all variables and fuctions only if these variables and functions exist in the scope which

the closure can visit.

Example 1:

var outerValue = 'ninja';
function outerFunction() {
if (outerValue == 'ninja') {
alert('I can see the ninja');
}
}
outerFunction();

Actually, we create a closure but we do not realize its advantage. Next example, we will do something complicated.

Example 2:

<script>
var outerValue = 'ninja';
var later;
function outerFunction() {
var innerValue = 'samural';
function innerFunction() {
alert(outerValue);
alert(innerValue);
}
later = innerFunction;
}
outerFunction();
later();
</script>

Now, we can see something awesome to the closure. 

When we create innerFunction in outerFunction, we not only create the inner function but also  create a closure which includes the annousement of the inner function and all the variables in the scope that the closure can visit.