javascript 闭包理解例子

Posted 牛顿的小脑

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

以上是关于javascript 闭包理解例子的主要内容,如果未能解决你的问题,请参考以下文章

对JavaScript中闭包的理解

javascripts闭包的理解

javascript闭包的基础理解

深入理解 Javascript 中的闭包

深入理解 Javascript 中的闭包

JavaScript 经典之一 闭包