ES6—30:一文搞懂闭包

什么是闭包?

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

闭包的主要作用

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

闭包应用1(利用闭包的方式得到当前小li的索引号)

闭包应用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>

猜你喜欢

转载自blog.csdn.net/sinat_41696687/article/details/113957083