闭包
概念
在计算机科学中,闭包(英语:Closure),又称词法闭包(Lexical Closure)或函数闭包(function closures),只要出现引用了外部变量的函数,那么这个现象就叫做闭包
作用
- 让数据变得更加的安全
- 优化代码
- 函数内返回了另外一个函数
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>闭包概念</title>
<style>
.box {
width: 200px;
height: 200px;
background-color: rgb(24, 159, 200);
}
</style>
</head>
<body>
<div class="box"></div>
<button>点我</button>
</body>
<script>
const box = document.querySelector(".box");
box.nextElementSibling.onclick = function () {
box.style.backgroundColor = "green";
// 广义闭包: 函数内部用到了外部变量
};
// 狭义闭包( 编程中真正用上的效果: 也是面试的时候想要得到的答案)
// 函数内部 返回一个函数: 在返回的函数的内部 用到了外部函数的局部变量: 狭义闭包
function outer() {
let data = [1, 2, 3, 4, 5];
let inner = function () {
// inner函数内部, 用到了外部函数 outer的局部变量 data: 狭义闭包
data.forEach(function (item, index) {
console.log(item, index);
});
};
return inner;
}
const res = outer();
console.log(res); // 到47行代码执行的时候: outer函数执行结束了吗? 肯定执行完了
res();
// 总结
// 为什么要有狭义闭包? 局部变量不会被污染: 数据是安全的
// 从代码角度出发: 闭包 会让代码变得复杂
// 闭包缺点: 外部函数执行结束需要被销毁掉所占内存, 但是内部函数因为占用关系: 导致外部函数自己的局部变量不能被销毁: 内存一直被占用
// 解决方案: 释放占用内部函数的外部变量: res
// 面试
// 1. 知道闭包吗?
// 回答: 知道
// 2. 解释一下什么是闭包?
// 回答: 广义闭包,闭包本意 函数内部用到了外部变量; 通常编程所说闭包是狭义闭包: 函数内部有一个函数,占用了外部函数的局部变量, 这种现象叫做狭义闭包
// 3. 闭包有什么用?
// 回答: 闭包的主要作用, 让数据变得安全, 数据保存在外部函数的局部变量中: 外部不可修改, 数据是安全的
// 4. 闭包有什么缺点?
// 回答: 闭包因为内部函数占用外部局部变量, 内部函数会以返回值的形式返回给外部去调用: 外部变量占用内部函数, 内部函数占用外部函数的局部变量: 导致 外部函数的数据的内存得不到释放: 占用内存
// 5. 如何解决内存占用问题?
// 回答: 如果内部函数被外部占用是一次性的, 那么用完就让外部变量(全局)不要指向内部函数(重新赋值), 就会释放内存(先释放内部函数, 内部函数释放外部局部变量占用). 如果是长期使用, 那就不可避免
</script>
</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>闭包应用</title>
</head>
<body>
<h1></h1>
<button>点我</button>
</body>
<script>
// 获取相关元素
const h1 = document.querySelector("h1");
const btn = document.querySelector("button");
// 安全方式:闭包
function getName() {
// 数据
let arr = [{ name: "金" }, { name: "木" }, { name: "水" }, { name: "火" }, { name: "土" }];
// 定义变量下标
let index = -1;
// 闭包实现,内部函数
return () => {
// 改变 index
index++;
// index不能超过arr.length
index = index == arr.length ? 0 : index;
// 返回index对应的数据
return arr[index].name;
};
}
// 闭包函数
const getInfo = getName();
// 默认显示
h1.innerText = getInfo();
// 点击事件
btn.onclick = function () {
h1.innerText = getInfo();
};
</script>
</html>