实际开发中闭包的应用

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

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
posted @ 2019-04-04 15:19  木石天涯  阅读(1312)  评论(0编辑  收藏  举报