mortal-cultivation-biography / daydayup

A FE interview-questions collection repo.
8 stars 0 forks source link

实现 apply/call/bind #37

Open nmsn opened 1 year ago

nmsn commented 1 year ago

如题

nmsn commented 1 year ago

apply

Function.prototype.myApply = function(obj, args) {
  const context = obj || window;

  context.fn = this;

  cosnt result = context.fn(...args);

  delete context.fn;

  return result;
}

call

Function.prototype.newCall = function(obj, ...args) {
  const context = obj || window;

  context.fn = this;

  cosnt result = context.fn(...args);

  delete context.fn;

  return result;
}

bind

Function.prototype.myBind = function(obj, ...args) {
  const fn = this;

  // 真正返回的函数
  return function exec(...args2) {

    return fn.apply(
    // 重点就在于这句话
    // 前半句判断是返回的函数当作实例方法执行时
    // 后半句为传入的绑定对象
     this instanceof exec ? this : obj,
     [...args,...args2]
    )
  }
}