闭包

补充: 极客时间

看着简单,实际隐藏了很多东西

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function count(){
let countNum = 0
return () => {
return ++countNum
}
}
//独立
console.log((count())()); //1
console.log((count())()); //1
console.log((count())()); //1
//闭包
let countFunc = count()
console.log(countFunc()); //1
console.log(countFunc()); //2
console.log(countFunc()); //3

直接写成自执行函数,更加简单

1
2
3
4
5
6
7
8
const countUp = (() => {
let count = 0;
return () => {
return ++count;
};
})();
console.log(countUp()); // 1
console.log(countUp()); // 2

闭包和this

1
2
3
4
5
6
7
8
9
10
var name = "The Window"; 
var object = {
name : "My Object",
getNameFunc : function(){
return function(){
return this.name;
};
}
};
alert(object.getNameFunc()()); //"The Window"(在非严格模式下)

上述代码,看似利用闭包得到了想要的this指向,实际上并不是
每个函数在被调用时都会自动取得两个特殊变量:this 和 arguments。内部函数在搜索这两个变量时,只会搜索到其活动对象为止,因此永远不可能直接访问外部函数中的这两个变量

控制台看闭包

一图胜千言

image-20210720105848139