登录  /  注册
首页 > web前端 > js教程 > 正文
js闭包使用详解
php中世界最好的语言
发布: 2018-04-28 11:56:39
原创
1235人浏览过

这次给大家带来js闭包使用详解,js闭包使用的注意事项有哪些,下面就是实战案例,一起来看一下。

closure is the combination of a function and the lexical environment within which that function was declared.

闭包是一个函数和其内部公开变量的环境的集合.

简单而言, 闭包 = 函数 + 环境

第一个闭包的例子

function init() {
 var name = 'Mozilla'; // name is a local variable created by init
 function displayName() { // displayName() is the inner function, a closure
 alert(name); // use variable declared in the parent function 
 }
 displayName(); 
}
init();
because inner functions have access to the variables of outer functions, displayName() can access the variable name declared in the parent function, init().
登录后复制

其实这个栗子很简单,displayName()就是init()内部的闭包函数,而为啥在displayName内部可以调用到外部定义的变量 name 呢,因为js内部函数有获取外部函数中变量的权限。

第二个例子

var data = [
 {'key':0},
 {'key':1},
 {'key':2}
];
function showKey() {
 for(var i=0;i<data.length;i++) {
   setTimeout(function(){
    //console.log(i); //发现i输出了3次3
   //console.log(this); // 发现 this 指向的是 Window
   data[i].key = data[i].key + 10;
   console.log(data[i].key)
   }, 1000);
 }
}
showKey();
登录后复制

上面这个例子可以正确输出 10 11 12 吗?

答案是:并不能,并且还会报语法错误....

console.log(i); 发现i输出了3次3,也就是说,在setTimeout 1000毫秒之后,执行闭包函数的时候,for循环已经执行结束了,i是固定值,并没有实现我们期望的效果。

console.log(this); 发现 this 指向的是 Window,也就是说,在函数内部实现的闭包函数已经被转变成了全局函数,存储到了内存中。

所以需要再定义一个执行函数

var data = [
 {'key':0},
 {'key':1},
 {'key':2}
];
function showKey() {
 var f1 = function(n){
  data[i].key = data[i].key + 10;
  console.log(data[i].key)
 }
 for(var i=0;i<data.length;i++) {
   setTimeout(f1(i), 1000);
 }
}
showKey();
// 得到预期的 10 11 12
登录后复制

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

Vue自定义动态组件使用详解

js使用分时函数步骤详解

以上就是js闭包使用详解的详细内容,更多请关注php中文网其它相关文章!

相关标签:
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 技术文章
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2023 //m.sbmmt.com/ All Rights Reserved | 苏州跃动光标网络科技有限公司 | 苏ICP备2020058653号-1

 | 本站CDN由 数掘科技 提供

登录PHP中文网,和优秀的人一起学习!
全站2000+教程免费学