概念
在計算機科學中,閉包(英語: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>
上一章:JavaScript 進階第七章(es6中的class)
下一章:JavaScript 進階第九章(原型鏈繼承)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/296904.html
標籤:其他
