当前位置: 首页 > news >正文

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.

相关文章:

  • 客户端putty, xshell连接linux中vim的小键盘问题
  • 2016蘑菇街编程题5题
  • C指针(二)
  • 用Python开发自动化测试脚本
  • git简单命令
  • 程序员健康Tips
  • 如何从mysql备份中提取单张表数据
  • AVAudioSessionCategory说明
  • 一个Android项目多线程下载模块开源库:AndroidFileDownloader
  • Azkaban的Web Server源码探究系列12: 首页之前的跳转
  • 学习之路-现代密码学基础-001
  • 使用hadoop实现关联商品统计
  • 链表的逆置
  • 帧间提取水印
  • 面试遇到的一些题
  • 【402天】跃迁之路——程序员高效学习方法论探索系列(实验阶段159-2018.03.14)...
  • 【跃迁之路】【699天】程序员高效学习方法论探索系列(实验阶段456-2019.1.19)...
  • create-react-app做的留言板
  • C学习-枚举(九)
  • iOS仿今日头条、壁纸应用、筛选分类、三方微博、颜色填充等源码
  • session共享问题解决方案
  • Spring声明式事务管理之一:五大属性分析
  • 阿里云爬虫风险管理产品商业化,为云端流量保驾护航
  • 大数据与云计算学习:数据分析(二)
  • 记录:CentOS7.2配置LNMP环境记录
  • 技术发展面试
  • - 语言经验 - 《c++的高性能内存管理库tcmalloc和jemalloc》
  • 中文输入法与React文本输入框的问题与解决方案
  • 【云吞铺子】性能抖动剖析(二)
  • ​人工智能书单(数学基础篇)
  • #pragma once与条件编译
  • (NSDate) 时间 (time )比较
  • (zhuan) 一些RL的文献(及笔记)
  • (阿里巴巴 dubbo,有数据库,可执行 )dubbo zookeeper spring demo
  • (分享)一个图片添加水印的小demo的页面,可自定义样式
  • (附源码)springboot掌上博客系统 毕业设计063131
  • (力扣)循环队列的实现与详解(C语言)
  • (免费领源码)python+django+mysql线上兼职平台系统83320-计算机毕业设计项目选题推荐
  • (三) prometheus + grafana + alertmanager 配置Redis监控
  • (已解决)报错:Could not load the Qt platform plugin “xcb“
  • ******IT公司面试题汇总+优秀技术博客汇总
  • ******之网络***——物理***
  • .NET Core IdentityServer4实战-开篇介绍与规划
  • .net core MVC 通过 Filters 过滤器拦截请求及响应内容
  • .net framwork4.6操作MySQL报错Character set ‘utf8mb3‘ is not supported 解决方法
  • .net 桌面开发 运行一阵子就自动关闭_聊城旋转门家用价格大约是多少,全自动旋转门,期待合作...
  • .net网站发布-允许更新此预编译站点
  • /3GB和/USERVA开关
  • /使用匿名内部类来复写Handler当中的handlerMessage()方法
  • @javax.ws.rs Webservice注解
  • @Repository 注解
  • [ 渗透测试面试篇 ] 渗透测试面试题大集合(详解)(十)RCE (远程代码/命令执行漏洞)相关面试题
  • []AT 指令 收发短信和GPRS上网 SIM508/548
  • [100天算法】-每个元音包含偶数次的最长子字符串(day 53)
  • [20170705]diff比较执行结果的内容.txt