闭包:闭包是一个组合,一个函数以及它捆绑的周边环境状态的引用组成的组合
闭包 = 函数 + 这个函数捆绑的周边环境状态的引用
闭包的表现形式
1、函数作为参数
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
</body>
<script>
// 函数作为参数
let a = 1;
function fn(){
console.log(a);
}
function fn2(callback){
let a = 2;
callback();//输出:1,
// 回调函数定义时的作用域链寻找a
// 而不是在使用时的作用域链中寻找a
}
fn2(fn);
</script>
</html>
2、函数作为返回值
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
</body>
<script>
// 函数作为返回值
function fn(){
let a = 1;
return function(){
console.log(a);
}
}
let f = fn();
let a = 2;
f();//输出:1
</script>
</html>
闭包的使用
1、使用闭包打造一个cache工具
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
</body>
<script>
function cache(){
let data = {};
return {
set(key,value){
data[key] = value;
},
get(key){
return data[key];
}
}
}
let c = cache();
c.set('name','jack');
console.log(c.get('name'));
</script>
</html>
2、使用闭包手写bind
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
</body>
<script>
let person = {
name:'jack',
}
function fn(a,b,c,d){
console.log(this.name);
console.log(a,b,c,d);
return a + b + c + d;
}
Function.prototype.myBind = function(obj,...args){
let self = this;//调用myBind方法的方法
return (...args2) => {
return self.call(obj,...args,...args2);
}
}
let f = fn.myBind(person,1,2);
let res = f(3,4);
console.log(res);
</script>
</html>
输出: