闲来无事,回顾一下这些经典面试手写代码题。

bind

  • 函数中的this是有属于调用者的,所以使用传入的target来调用当前函数即可
  • bind 的返回值为 function,记得 return 返回值。
Function.prototype._bind = function (thisArg, ...rest) {
  if (typeof thisArg === 'undefined') thisArg = window || global
  thisArg.fn = this;
  return function () {
    const res = thisArg.fn(...rest);
    delete thisArg.fn
    return res;
  }
}

call

  • bind区别 他是直接执行
Function.prototype._call = function (thisArg, ...rest) {
  if (typeof thisArg === 'undefined') thisArg = window || global;
  thisArg.fn = this;
  const res = thisArg.fn(...rest);
  delete thisArg.fn
  return res;
}

apply

  • bind区别 他是直接执行,参数为数组
  • apply 应该是问的比较多的吧
Function.prototype._apply = function (thisArg, rest) {
  if (typeof thisArg === 'undefined') thisArg = window || global;
  thisArg.fn = this;
  const res = thisArg.fn(...rest);
  delete thisArg.fn
  return res;
}

new

  • 实现 new 需要注意几点
  • new 构造函数的返回值,为基础类型则返回this,使用引用类型则按你的返回。
  • 原型链
function _new(constructor, ...rest) {
  const instance = {};
  instance.__proto__ = constructor.prototype;
  // 处理构造函数对应的this
  const res = constructor.apply(instance, rest);
  if (typeof res === 'object' || typeof res === 'function') return res;
  return instance;
}


function P() {
  this.a = '1'
}

P.prototype.a = '1'

const p1 = _new(P);

console.log(p1 instanceof P); // true