实际开发中闭包的应用

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

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
原文地址:https://www.cnblogs.com/mushitianya/p/10655039.html