JavaScript 进阶第八章(闭包)

概念

计算机科学中,闭包(英语:Closure),又称词法闭包(Lexical Closure)或函数闭包(function closures),只要出现引用了外部变量的函数,那么这个现象就叫做闭包

作用

  1. 让数据变得更加的安全

  2. 优化代码

  3. 函数内返回了另外一个函数

代码演示 

不使用闭包

<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 进阶第九章(原型链继承)

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

海海呐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值