<!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>
<h1>闭包的应用</h1>
<input type="text" class="input" />
<script>
// 全局变量
let a = "这么久没见";
function fn1() {
let b = 1;
console.log(a, 111);
// 能访问a
}
// console.log(b,222);
fn1();
// AO active object 创建的临时变量对象
//防抖与节流
// 防抖 : 一定时间内只允许一个事件
// 节流 :多次变为一次
// 防抖函数
function antiShake(fn, wait) {
let timeOut = null;
return (args) => {
if (timeOut) clearTimeout(timeOut);
timeOut = setTimeout(fn, wait);
};
}
function demo2() {
console.log("后台大哥,我要请求数据了");
}
let handerInput = document.querySelector(".input");
handerInput.addEventListener("input", antiShake(demo2, 1000)); //1s中请求一次
// 模块化
// 通过闭包实现 私有方法 私有变量
let makeCounter = function () {
let privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
add: function () {
changeBy(1);
},
reduce: function () {
changeBy(-1);
},
value: function () {
return privateCounter;
},
};
};
let res1 = makeCounter();
let res2 = makeCounter();
// 词法作用域
res1.add();
res1.add();
res2.add();
res2.reduce();
console.log(res1.value); // 2
console.log(res2.value); // 0
// 闭包提供了面向对象编程的好处 ----数据的隐藏和封装
</script>
</body>
</html>
闭包的应用
最新推荐文章于 2022-08-31 10:47:17 发布