zoukankan      html  css  js  c++  java
  • javascript 闭包 (How do JavaScript closures work?)

    Whenever you see the function keyword within another function, the inner function has access to variables in the outer function.

    function foo(x) {
     
    var tmp = 3;
     
    function bar(y) {
        alert
    (x + y + (++tmp));
     
    }
      bar
    (10);
    }
    foo
    (2)

    This will always alert 16, because bar can access the x which was defined as an argument to foo, and it can also access tmp from foo.

    That is not a closure. A closure is when you return the inner function. The inner function will close-over the variables of foo before leaving.

    function foo(x) {
     
    var tmp = 3;
     
    return function (y) {
        alert
    (x + y + (++tmp));
     
    }
    }
    var bar = foo(2); // bar is now a closure.
    bar
    (10);

    The above function will also alert 16, because bar can still refer to x and tmp, even though it is no longer directly inside the scope.

    However, since tmp is still hanging around inside bar's closure, it is also being incremented. It will be incremented each time you call bar.

    (Note for your 6 year old: It is possible to create more than one closure function, either by returning a list of them or by setting them to global variables. All of these will refer to the same x and the same tmp, they don't make their own copies.)

    Edit: And now to explain the part that isn't obvious.

    Here the number x is a literal number. As with other literals in JavaScript, when foo is called, the number x is copied into foo as its argument x.

    On the other hand, JavaScript always uses references when dealing with Objects. If say, you called foowith an Object, the closure it returns will reference that original Object!

    function foo(x) {
     
    var tmp = 3;
     
    return function (y) {
        alert
    (x + y + tmp);
        x
    .memb = x.memb ? x.memb + 1 : 1;
        alert
    (x.memb);
     
    }
    }
    var age = new Number(2);
    var bar = foo(age); // bar is now a closure referencing age.
    bar
    (10);

    As expected, each call to bar(10) will increment x.memb. What might not be expected, is that x is simply referring to the same object as the age variable! After a couple of calls to barage.memb will be 2!

    This is the basis for memory leaks with HTML objects, but that's a little beyond the scope of this, ahem, article, ahem. http://stackoverflow.com/questions/111102#112265

  • 相关阅读:
    Redis命令总结
    jvisualvm远程监控Tomcat
    CentOS6安装glibc-2.14,错误安装libc.so.6丢失急救办法
    vsan分布式存储数据恢复全过程
    linux文件系统损坏修复方法,亲测可用
    案例讲解服务器硬盘离线数据恢复方法-数据恢复
    服务器数据丢失恢复过程
    数据恢复工程师讲述Linux服务器数据恢复过程
    了解这一点轻松解决Oracle数据库系统报错问题
    浅析RAID0/1安全差别及处理数据安全的应对方式
  • 原文地址:https://www.cnblogs.com/yhql/p/2151607.html
Copyright © 2011-2022 走看看