当前位置:网站首页>什么是闭包函数
什么是闭包函数
2022-06-23 09:09:00 【Crazy_GirlLL】
什么是闭包函数
1、定义和用法:当一个函数的返回值是另外一个函数,而返回的那个函数如果调用了其父函数内部的其它变量,如果返回的这个函数在外部被执行,就产生了闭包。(关于概念博主摘抄以上几点,详情查看 百度百科)
2、表现形式:使函数外部能够调用函数内部定义的变量。
案例1:根据作用域链的规则,底层作用域没有声明的变量,会向上一级找,找到就返回,没找到就一直找,直到window的变量,没有就返回undefined。这里明显变量a 是函数内部的fun 的那个变量a 。
(变量的作用域分类:全局变量和局部变量。)
*注:*函数内部声明变量的时候,一定要使用var命令。如果不用的话,你实际上声明了一个全局变量!

案例2:与案例一不同的是fun2闭包对象中,此时调用的函数nbfun2 只是内部函数的方法, 所以我们定义一个变量name调用闭包函数对象调用后,将nbfun2函数赋值给name变量;然后使用name()方式进行调用.

案例3:
第一步:当我们调用闭包fun3对象时,一个传入1 一个传入2 将返回的函数对象分别给变量a b;
第二步:此时从控制台输出内部函数调用 分别传入1 2 值给a1的y b2的y;
(此时也就是说 a1 b2 都是闭包 他们共享相同的函数定义,但是保存在了不同的环境中)
在a1中 x=1, b2中 x=2;

总结:
使用闭包主要是为了设计私有的方法和变量。闭包的优点是可以避免全局变量的污染,缺点是闭包会常驻内存,会增大内存使用量,使用不当很容易造成内存泄露。在js中,函数即闭包,只有函数才会产生作用域的概念
闭包有三个特性:
函数嵌套函数
函数内部可以引用外部的参数和变量
参数和变量不会被垃圾回收机制回收
边栏推荐
- Redis学习笔记—Pipeline
- An idea of using keep alive to cache data in vue3 form pages
- 点击添加下拉框
- Geoserver添加mongoDB数据源
- H-index of leetcode topic analysis
- Leetcode topic analysis count primes
- 【学习资源】理解数学和热爱数学
- Redis learning notes - data type: ordered set (Zset)
- MySQL fault case | error 1071 (42000): specified key was too long
- Redis learning notes - traverse key
猜你喜欢

披萨订购设计----简单工厂模式

Custom tag - JSP tag Foundation
Redis learning notes - data type: hash

173. Binary Search Tree Iterator

三层架构与SSM之间的对应关系

"Coach, I want to play basketball" -- AI Learning Series booklet for students who are making systems

GeoServer adding mongodb data source

Servlet-02 生命周期

【云原生 | Kubernetes篇】Kubernetes原理与安装(二)

636. Exclusive Time of Functions
随机推荐
528. Random Pick with Weight
Simple student management
[QNX Hypervisor 2.2用户手册]6.2 网络
Structure binary tree from inorder and postorder traversal for leetcode topic analysis
Redis学习笔记—数据类型:字符串(string)
16.系统启动流程
[learning resources] understand and love mathematics
Tencent cloud arm server evaluation practice
Balls and cows of leetcode topic analysis
The fourth online workshop review
“教练,我想打篮球“ —— 给做系统的同学们准备的 AI 学习系列小册
The sliding window of the force button "step by step" (209. sub array with the smallest length, 904. fruit basket)
Batch generation of code128- C barcode
New engine, new capability, new experience, Tencent host security flagship release
JSP入门总结
The results of CDN node and source station are inconsistent
An idea of using keep alive to cache data in vue3 form pages
523. Continuous Subarray Sum
Custom tags - JSP tag enhancements
三层架构与SSM之间的对应关系