好好爱自己!

javascript 闭包理解例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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 的话;

1
2
3
4
5
6
7
8
9
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!).
1
2
3
4
5
6
7
8
9
10
11
function sayHello(name){
   var text = "Hello " + name;
   function say(){            //函数里面定义函数
     console.log(text);
   }
   return say;
}
 
var aa = sayHello('ysr');
 
aa();              // Hello ysr;

  

1
2
3
4
5
6
7
8
9
10
11
function sayHello(name){
   var text = "Hello " + name;
  var say = function(){          //the anonymous function
     console.log(text);
   }
   return say;
}
 
var aa = sayHello('yangyu');
 
aa(); 

  

1
2
3
4
5
6
7
8
9
10
11
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.

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

1
2
3
4
5
6
7
8
9
10
//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 scopefunction 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: 

1
2
3
4
5
6
7
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!

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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.

posted @   立志做一个好的程序员  阅读(455)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现

不断学习创作,与自己快乐相处

点击右上角即可分享
微信分享提示