天天看点

ES6—30:一文搞懂闭包

什么是闭包?

闭包是一种有权访问另一个函数作用域中变量的函数。

https://link.juejin.cn/?target= 闭包的主要作用

答:延伸了变量的作用范围。

https://link.juejin.cn/?target= 闭包应用1(利用闭包的方式得到当前小li的索引号)

ES6—30:一文搞懂闭包

闭包应用2(计算打车价格)

<script>
// 计算打车价格
// 打车起步价13(3公里内),之后每多一公里增加5块钱,用户输入公里数就可以计算
// 打车价格,如果有拥堵的情况,总价格多收取10块钱的拥堵费
var user_price = (function () {
    var start = 13;
    var total = 0;
    return {
        price: function (n, flag) {
            if (n <= 3) {
                total = start;
            } else {
                total = start + (n - 3) * 5;
            }
            if (flag == true) {
                total = total + 10;
            } else {
                total = total;
            }
            return total;
        }
    }
})();
console.log(user_price.price(5, true));
console.log(user_price.price(1, false));
</script>      

作者:Always_positive

链接:

https://juejin.cn/post/6948665080426790925

来源:稀土掘金

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

继续阅读