基础知识

125 阅读1分钟
  • 基础版本防抖
   function debounce(callback, delay) {
      let timer;
      args = arguments;
      
      return function () {
        let context = this;
        clearTimeout(timer);
        timer = setTimeout(function () {
          callback.call(context, args);
        }, delay);
      };
      
    }
  • 升级版防抖,选择是否立即执行
function debounce(callback, delay, immediate) {
      let timer;
      args = arguments;
      return function () {
        let context = this;
        clearTimeout(timer);
        if (immediate) {
          let nowDoing = !timer;
          timer = setTimeout(() => {
            timer = null;
          }, delay);
          // 立即执行
          nowDoing && callback.apply(context, args);
        } else {
          // 不会立即执行
          timer = setTimeout(function () {
            callback.apply(context, args);
          }, delay);
        }
      };
    }
  • 基础防抖demo 刚接触的时候,一直不明白timer不是会创建很多次吗,后来看了又看,才发现原来是基础知识不牢固的问题,timer根本就不会创建很多次,因为在点击之前,debounce 就会执行一次了,这个时候,就创建了timer了,下一次点击的时候,就不存在debounce了,此时只有debounce里面return的一个匿名函数了
<!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>
    <button class="btn">按钮</button>
  </body>
  <script>
    let btn = document.getElementsByClassName("btn")[0];
    btn.onclick = debounce(doThing, 1000);

    function doThing() {
      console.log(1);
    }

    function debounce(callback, delay) {
      args = arguments;
      let timer;
      return function () {
        clearTimeout(timer);
        let context = this;
        timer = setTimeout(function () {
          callback.apply(context, args);
        }, delay);
      };
    }
  </script>
</html>

  • 基础版本节流---顾尾不顾头
function throttle(callback, delay) {
      let timer;
      args = arguments;
      return function () {
        let context = this;
        if (!timer) {
          timer = setTimeout(function () {
            timer = null;
            callback.apply(context, args);
          }, delay);
        }
      };
    }
  • 手写call
let obj1 = {
  name: "小明",
  age: 18,
  say(sex) {
    return `我的名字叫${this.name},我今年${this.age}了,我是一个${sex}生`;
  },
};

let obj2 = {
  name: "小红",
  age: 28,
};

Function.prototype.myCall = function (obj, args) {
  obj = obj || window;
  let key = Symbol();
  obj[key] = this;
  const res = obj[key](...args);
  delete obj[key];
  return res;
};

console.log(obj1.say("男")); //        我的名字叫小明,我今年18了,我是一个男生

console.log(obj1.say.myCall(obj2, "女")); //      我的名字叫小红,我今年28了,我是一个女生