SOURCE

console 命令行工具 X clear

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

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>

  <script>
    // 二.留下添加折扣和删除折扣的接口
    const calcPrice = (function () {
      // 折扣策略
      const sale = {
        '100_10': function (price) { return price -= 10 },
        '200_25': function (price) { return price -= 25 },
        '80%': function (price) { return price *= 0.8 }
      }

      function calcPrice(price, type) {
        if (!sale[type]) return '没有这个折扣'
        return sale[type](price)
      }

      // 把函数当作一个对象, 象里面添加一些成员
      // 专门用来添加折扣
      calcPrice.add = function (type, fn) {
        if (sale[type]) return '该折扣已经存在'
        sale[type] = fn
        return '添加成功'
      }
      // 删除一个折扣
      calcPrice.del = function (type) {
        delete sale[type]
      }

      return calcPrice
    })();


    // 使用的时候,添加一个折扣
    calcPrice.add('70%', function (price) { return price *= 0.7 })
    const res = calcPrice(320, '70%')
    console.dir(res) //=> 320 * 0.7 = 224

    calcPrice.del('100_10')
    const res2 = calcPrice(320, '100_10')
    console.log(res2) //=> 没有这个折扣

    // 一、最简单的一个实现,业务问题使用这个也是可以的,只是不够完整
    // 一旦加一种折扣,每次添加删除折扣都需要手动改

    // 接收两个参数, 价格, 折扣种类
    // function calcPrice(price, type) {
    //   if (type === '100_10') {
    //     price -= 10
    //   } else if (type === '200_25') {
    //     price -= 25
    //   } else if (type === '80%') {
    //     price *= 0.8
    //   } else {
    //     console.log('没有这种折扣')
    //   }

    //   return price
    // }

    // // 将来使用的时候
    // const res = calcPrice(320, '70%')
    // console.log(res)
  </script>
</body>

</html>