大佬教程收集整理的这篇文章主要介绍了JavaScript 进阶第八章(闭包),大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
在计算机科学中c;闭包(英语:Closure)c;又称词法闭包(Lexical Closure)或函数闭包(function closures)c;只要出现引用了外部变量的函数,那么这个现象就叫做闭包@H_607_13@
让数据变得更加的安全
优化代码
函数内返回了另外一个函数
<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>
@H_607_13@
<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>
@H_607_13@
以上是大佬教程为你收集整理的JavaScript 进阶第八章(闭包)全部内容,希望文章能够帮你解决JavaScript 进阶第八章(闭包)所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。