常见面试手写题,promise会单出一篇写,这篇先不讲

132 阅读1分钟

手写instanceOf

注释:
  • 循环到尽头就是left==null;
function myInstanceOf(left, right) {
  let prototype = right.prototype;
  left = left.__proto__;
  while (true) {
    if (left === null) return false;
    if (left === prototype) return true;
    left = left.__proto__;
  }
}

手写call

注释:
  • 核心是将此函数当作上下文参数(context)的一个属性去执行;
  • 保证定义的新属性在context上没出现过,所以使用Symbol
  • 返回值是执行结果
Function.prototype.myCall = function (context) {
  let fn = Symbol();
  context = context || window;
  context[fn] = this;
  const args = [...arguments].slice(1);
  const result = context[fn](...args);
  delete context[fn];
  return result;
};

手写bind

注释:
  • 将this保存,this目前指的是一个function, 因为后面会返回一个新的function,在新的function中,this指向新的对象
  • 记录传给bind的后续参数例如下面的arg1;
  • 记录传给执行函数的参数,例如下面的arg2:
  • fn = u.bind(context,arg1);fn(arg2);
  • 合并两个参数,调用apply
Function.prototype.myCall = function (context) {
  let fn = Symbol();
  context = context || window;
  context[fn] = this;
  const args = [...arguments].slice(1);
  const result = context[fn](...args);
  delete context[fn];
  return result;
};

手写new

function myNew(con) {
  let obj = {};
  obj.__proto__ = con.prototype;
  con.call(obj);
  return obj;
}

手写防抖

function debounce(fn, time) {
  let timer = null;
  return function () {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn();
      timer = null;
    }, time);
  };
}

手写节流

function throttle(fn, time) {
  let startTime = new Date();
  return function () {
    let lastTime = new Date();
    if (lastTime - startTime > time) {
      fn();
      startTime = lastTime;
    }
  };
}