闭包案例 计算打车价格

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 闭包应用 计算打车价格
        // function fn(){

        // }

        var car = (function() {
            var start = 13; // 起步价
            var total = 0; // 总价

            return {
                // 正常的价格
                price: function(n) {
                    if (n <= 3) {
                        total = start;
                    } else {
                        total = start + (n - 3) * 5;
                    }
                    return total;
                },
                // 拥堵之后的价格
                yd: function(flag) {
                    return flag ? total + 10 : total;
                }
            }
        })();
        console.log(car.price(5)); // 23
        console.log(car.yd(true)); // 33
        console.log(car.price(1)); // 13
        console.log(car.yd(false)); // 13
    </script>
</body>

</html>
posted @ 2020-06-08 21:03  EricBlog  阅读(190)  评论(0编辑  收藏  举报