闭包的实际应用,主要是用来封装变量。即把变量隐藏起来,不让外面拿到和修改。

function isFirstLoad() {
    var _list = []

    return function (id) {
        if (_list.indexOf(id) >= 0) {
            return false
        } else {
            _list.push(id)
            return true
        }
    }
}

// 使用
var firstLoad = isFirstLoad()
firstLoad(10) // true
firstLoad(10) // false
firstLoad(20) // true

相关文章:

  • 2021-06-05
  • 2021-11-01
  • 2022-12-23
  • 2022-12-23
  • 2021-09-08
  • 2021-12-19
  • 2021-09-21
猜你喜欢
  • 2021-10-11
  • 2021-05-30
  • 2021-04-02
  • 2021-09-24
  • 2022-01-29
  • 2022-12-23
  • 2021-08-20
相关资源
相似解决方案