封装函数用于复用

59 阅读2分钟

1.封装时间函数用于复用,format用于规定输出时间样式

function dateFormat(date, format = "YYYY-MM-DD HH:mm:ss") {
  const config = {
    YYYY: date.getFullYear(),
    MM: date.getMonth() + 1,
    DD: date.getDate(),
    HH: date.getHours(),
    mm: date.getMinutes(),
    ss: date.getSeconds()
  };
  for (const key in config) {
    format = format.replace(key, config[key]);
  }
  return format;
}
console.log(dateFormat(new Date(), "YYYY年MM月DD日"));//2023年8月31日

2.js构造函数封装提示

1.创建构造函数 创建div,追加类名,为挂载函数绑定参数
2.在构造函数原型上挂载open方法 append在页面追加创建的div
3.获取点击按钮,创建实例化对象,传递对应参数。调用open方法
4.关闭方法:需要创建打开追加div时就监听x;创建关闭方法 
注意:4关闭时是移除相应元素 this.box.remove()
bug:box && box.remove()//注意:判断有则添加没有则删除 逻辑与中断
<!DOCTYPE html>
<html lang="en">

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

      width: 800px;
      margin: 0 auto;

    }

    .modal {

      margin: 100px auto;
      width: 200px;
      height: 100px;
      background-color: #eaeaea;
      border: 1px solid #CCC;
    }

    .header {
      display: flex;
      justify-content: space-between;
      margin: 10px;
    }

    .header span {
      cursor: pointer;
    }

    .body {
      line-height: 50px;
      text-align: center;

    }
  </style>
</head>

<body>
  <!-- 上面都是解释代码不是主要代码 -->
  <button class="login">登录</button>
  <button class="delete">删除</button>
  <button class="add">新增</button>
  <!-- <div class="modal">
    <div class="header">温馨提示<span>X</span>
    </div>
    <div class="body">您没有删除权限</div>
  </div> -->
  <script>
    //1.
    function Modal(title = '', message = '') {
      // console.log(title, message);
      //温馨提示 提示 x
      //创建div元素,添加类名
      this.modalBox = document.createElement('div');
      this.modalBox.className = 'modal';
      this.modalBox.innerHTML = `
      <div class="header">${title}<span>X</span>
      </div>
      <div class="body">${message}</div>
      `
      // console.log(this.modalBox);
    }
    // new Modal('温馨提示', '您没有删除权限');
    // new Modal('友情提示', '您还没有登录');
    //2.为构造函数原型上挂载open方法

    Modal.prototype.open = function () {
      //排他
      const box = document.querySelector('.modal')
      box && box.remove()//注意:判断有则添加没有则删除  逻辑与中断
      document.body.append(this.modalBox)//通过添加追加到页面 我也不知道为什么使用这个方法

      //获取监听x事件
      document.querySelector('.header span').addEventListener('click', () => {
        // alert('close')
        // console.log(this.modalBox);
        this.close();
      })
    }
    //关闭方法
    Modal.prototype.close = function () {
      this.modalBox.remove()//通过添加追加到页面 我也不知道为什么使用这个方法
    }
    //-------------------------------------------以上为核心js,下面是应用--------------------------
    //3.测试 点击删除按钮
    document.querySelector('.delete').addEventListener('click', function () {
      const del = new Modal('温馨提示', '您没有删除权限')
      //调用
      del.open();
    })
    //挂载打开

    //测试 点击登录按钮
    document.querySelector('.login').addEventListener('click', function () {
      const log = new Modal('友情提示', '您还没有登录')
      //调用
      log.open();
    })

    //4.关闭按钮 有了模态框,获取事件


    //add
    document.querySelector('.add').addEventListener('click', function () {
      const log = new Modal('温馨提示', '您还无法新增')
      //调用
      log.open();
    })
  </script>
</body>

</html>

3.手写节流(了解)

<!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>
  <div class="box" style="width: 400px;height: 400px;background-color:#ccc;"></div>
  <script>
    //节流思路:检测到移动后,执行函数,开启定时器,开启之后将不再接收其他
    const box = document.querySelector('.box')
    let i = 0;

    function mousemove() {
      box.innerHTML = i++;
    }
    function throttle(fn, t) {
      let timer = null;
      return function () {
        //防抖核心:每一次执行都将清理定时器
        // if (timer) clearTimeout(timer);
        // const timer = setTimeout(function () {
        //   fn();
        //   //执行一次就退出
        //   timer = null;
        // }, t)
        //节流核心:定时器不存在时创建,执行完后null
        if (!timer) {
          timer = setTimeout(function () {
            fn();
            timer = null;
          }, t)
        }
      }
    }
    // box.addEventListener('mousemove', _.throttle(mousemove, 2000));
    box.addEventListener('mousemove', throttle(mousemove, 1500))
  </script>
</body>

</html>

4.手写防抖(了解)

如何实现防抖?调用定时器
准备:创建鼠标移动事件的函数,监听鼠标事件
1.声明变量
2. return function(){}
3.如果存在定时器清除,如果不存在创建定时器
4.定时器中调用鼠标移动函数
<!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>
  <div class="box" style="width: 400px;height: 400px;background-color:#ccc;"></div>
  <div>防抖:单位时间内只执行最后一次,减少服务器请求压力</div>
  <script>
    
    const box = document.querySelector('.box')
    let i = 0;
    function mousemove() {
      box.innerHTML = i++;
    }
    //------------防抖---------
    //定时器
    function fn(f, t) {
      let timer;
      return function () {//相当于直接在监听事件后面调用函数
        if (timer) clearTimeout(timer)
        timer = setTimeout(function () {
          f();
        }, t)
      }
    }
    //------------防抖---------
    box.addEventListener('mousemove', fn(mousemove, 500))//最后一次执行的500毫秒后展示数据
    // 使用loadsh组件库:box.addEventListener('mousemove', _.debounce(mousemove, 500))


  </script>
</body>

</html>

5.封装过滤
01.根据是否包含在数组内数组过滤
传值、遍历数组、判断

 function except(array, excepts) {
      const newArray = [];
      for (const elem of array)
        if (!excepts.includes(elem)) newArray.push(elem);//传递过来的数据是否包含在数组中,如果没有则追加到新数组
      return newArray;
    }

    const array = ['h', 'i', 'j', 'k'];
    console.log(except(array, ['j'])); //[1,4]传入一个数组过去

02.根据回调函数过滤
传值、遍历数组、判断

 function except(array, callback) {
      const newArray = [];
      for (const item of array)
        if (callback(item) == true) newArray.push(item);//传递过来的数据是否包含在数组中,如果没有则追加到新的数组中
      return newArray;
    }

    const array = [40, 20, 10, 5];
    console.log(except(array, function (num) {
      return num > 15
    })); //传入一个函数过去