当不希望一个变量造成全局污染,又要常驻内存,就使用闭包
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
/* 当不希望一个变量造成全局污染,又常驻内存,就使用闭包 */
function create(){
let a = 100;
return function(){
console.log(a);
}
}
/* */
var fn = create();
fn();
/*
fn = function(){
console.log(a);
}
fn是全局变量,它没有调用a的内存就不会释放掉
*/
</script>
</body>
</html>
1、闭包
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
/* 使用一个闭包函数,可以设置和获取内存,但是没办法直接获取内存 */
function createCache(){
const data = {} //闭包中的数据是隐藏,不return外部没办法直接访问
return {
set:function(key,val){
data[key] = val
},
get:function(key){
return data[key];
}
}
}
var obj = createCache();
obj.set("name","cheng");
obj.set("age",12)
console.log(obj.get("age"))
</script>
</body>
</html>
2、闭包封装函数防抖
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="btn">btn</button>
<script>
var btn = document.getElementById("btn");
btn.addEventListener("click",debounce(function(){
console.log(this.id);
}))
function debounce(fn,delay=500){
let timer = null;
return function(){
if(timer){
clearTimeout(timer);
}
timer = setTimeout(()=>{
fn.call(this);
},delay)
}
}
</script>
</body>
</html>