ES6-30: Understanding closures in one article

What is a closure?

A closure is a function that has access to variables in the scope of another function .

The main function of closures

Answer: The scope of the variable is extended.

Closure application 1 (using the closure method to get the index number of the current small li)

Closure application 2 (calculate taxi price)

<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>

Guess you like

Origin blog.csdn.net/sinat_41696687/article/details/113957083