概念
在计算机科学中,闭包(英语:Closure),又称词法闭包(Lexical Closure)或函数闭包(function closures),只要出现引用了外部变量的函数,那么这个现象就叫做闭包
作用
- 让数据变得更加的安全
- 优化代码
- 函数内返回了另外一个函数
代码演示
不使用闭包
<body> <button>自增</button> <h1></h1> <script> const btn = document.querySelector("button"); const h1 = document.querySelector("h1"); let num = 0; let arr = [{ name: "上路" }, { name: "中路" }, { name: "射手" }, { name: "打野" }, { name: "辅助" }]; h1.innerText = arr[num].name; btn.onclick = function () { num++; if (num >= arr.length) { num = 0; } h1.innerText = arr[num].name; } </script> </body>
使用闭包
<body> <button>自增</button> <h1></h1> <script> const btn = document.querySelector("button"); const h1 = document.querySelector("h1"); function setElements() { let num = -1; let arr = [{ name: "上路" }, { name: "中路" }, { name: "射手" }, { name: "打野" }, { name: "辅助" }]; return function () { num++; if (num >= arr.length) { num = 0; } return arr[num].name; } } const getElement=setElements(); h1.innerText = getElement(); btn.onclick = function () { h1.innerText = getElement(); } </script> </body>