zoukankan      html  css  js  c++  java
  • javascript 闭包理解例子


    function Jquery(){ this.name = 'ysr'; this.sex = 'man'; return { x: this, age : 26 } } var b = new Jquery(); //b => {x:Jquery, age:26} //b.x = Jquery; //b.x.name = 'ysr'; //b.x.sex = 'man'


    var b = Jquery();
    //b.x = window;

      若果里面没return 的话;

    function Jquery(){
        this.name  = 'ysr';
        this.sex = 'man';
     
    
    }
    var a = new Jquery();
    
    //a={name:'ysr',sex:'man'}
    

      什么是闭包(closure function )

        Two one sentence summaries:

    • a closure is the local variables for a function — kept alive after the function has returned, or
    • a closure is a stack-frame which is not deallocated when the function returns (as if a 'stack-frame' were malloc'ed instead of being on the stack!).
    function sayHello(name){
       var text = "Hello " + name;
       function say(){            //函数里面定义函数
         console.log(text);
       }
       return say;
    }
    
    var aa = sayHello('ysr');
    
    aa();              // Hello ysr;
    

      

    function sayHello(name){
       var text = "Hello " + name;
      var say = function(){          //the anonymous function
         console.log(text);
       }
       return say;
    }
    
    var aa = sayHello('yangyu');
    
    aa();  
    

      

    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) { console.log(x + y + (++tmp)); // will log 16 } bar(10); } foo(2); //This will always log 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 a closure. A function doesn't have to return in order to be called a closure. Simply accessing variables outside of your immediate lexical scope creates a closure.

      上面这个例子,变一下, 返回出来。!!

    //The above function will also log 16, because bar can still refer to x and tmp, even though it is no longer directly inside the scope
    function foo(x) { var tmp = 3; return function (y) { console.log(x + y + (++tmp)); // will also log 16 } } var bar = foo(2); // bar is now a closure. bar(10); //16
    bar(10) //17

     The simplest example of a closure is this: 

    var a = 10;
    function test() {
      console.log(a); // will output 10
      console.log(b); // will output 6
    }
    var b = 6;
    test();
    

      

    When a JavaScript function is invoked, a new execution context is created. Together with the function arguments and the parent object, this execution context also receives all the variables declared outside of it (in the above example, both 'a' and 'b').

    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.

    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 foo with an object, the closure it returns will reference that original object!

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

      

    function makeKitchen () {
      var trashBags = ['A', 'B', 'C']; // only 3 at first
    
      return {
        getTrashBag: function() {
          return trashBags.pop();
        }
      };
    }
    
    var kitchen = makeKitchen();
    
    kitchen.getTrashBag(); // returns trash bag C
    kitchen.getTrashBag(); // returns trash bag B
    kitchen.getTrashBag(); // returns trash bag A
    

      

     

    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 referencing is the basis for memory leaks with HTML objects.

  • 相关阅读:
    OS第6次实验报告:使用信号量解决进程互斥访问
    操作系统第5次实验报告:内存管理
    OS第4次实验报告:文件系统
    OS第3次实验报告:命名管道
    Derby小记
    eclipse连接SQL Server2012
    录屏工具——Captura
    OS第2次实验报告:创建进程
    OS第1次实验报告:熟悉使用Linux命令和剖析ps命令
    第四次实验报告:使用Packet Tracer理解RIP路由协议
  • 原文地址:https://www.cnblogs.com/oxspirt/p/5343506.html
Copyright © 2011-2022 走看看