JavaScript基础第八章(闭包)

闭包概念

在计算机科学中,闭包(英语: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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值