zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    【如何使用翻译工具翻译网页】英语没过关的可以参考下。
    HTTP 请求报文和响应报文
    VIM+ctags+cscope用法
    Ubuntu下命令行访问网站
    mini_httpd的安装和配置
    堆排序(代码2)
    插入排序
    堆排序(代码1)
    快速排序
    Python中的控制流
  • 原文地址:https://www.cnblogs.com/zhuangzebo/p/8097552.html
Copyright © 2011-2022 走看看