最新文章专题视频专题问答1问答10问答100问答1000问答2000关键字专题1关键字专题50关键字专题500关键字专题1500TAG最新视频文章推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37视频文章20视频文章30视频文章40视频文章50视频文章60 视频文章70视频文章80视频文章90视频文章100视频文章120视频文章140 视频2关键字专题关键字专题tag2tag3文章专题文章专题2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章专题3
当前位置: 首页 - 科技 - 知识百科 - 正文

js闭包学习心得总结

来源:懂视网 责编:小采 时间:2020-11-27 22:16:41
文档

js闭包学习心得总结

js闭包学习心得总结:首先引用来自官网文档的定义: closure is the combination of a function and the lexical environment within which that function was declared. 闭包是一个函数和其内部公开变量的环境的集合. 简单而言, 闭包 = 函数 + 环境 第一个
推荐度:
导读js闭包学习心得总结:首先引用来自官网文档的定义: closure is the combination of a function and the lexical environment within which that function was declared. 闭包是一个函数和其内部公开变量的环境的集合. 简单而言, 闭包 = 函数 + 环境 第一个

首先引用来自官网文档的定义:

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

文档

js闭包学习心得总结

js闭包学习心得总结:首先引用来自官网文档的定义: closure is the combination of a function and the lexical environment within which that function was declared. 闭包是一个函数和其内部公开变量的环境的集合. 简单而言, 闭包 = 函数 + 环境 第一个
推荐度:
标签: js 体会 学习心得
  • 热门焦点

最新推荐

猜你喜欢

热门推荐

专题
Top