庄泽波の博客

好记性不如烂笔头

How Does Closure Work in Javascript?

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.

posted on 2017-12-24 10:55  庄泽波  阅读(172)  评论(0编辑  收藏  举报

导航