手写call、apply、bind

178 阅读1分钟

手写call、apply、bind

call

Function.prototype.myCall = function (content) {
    //判断是否为函数
    if (typeof this !== 'function') {
        thorw error('content is not a function')
    }
    //获取参数
    const args = [...arguments].slice(1);
    let results = null;
    //查看是否有传入指向对象
    content = content || window;
    //所指向的对象创建一个property等于调用myCall的对象
    content.fn = this;
    results = content.fn(...args);
    return results
}

apply

Function.prototype.myApply = function(content: any) {
  if (typeof this !== 'function') {
    throw new Error('is not a function');
  }
  const args = [...arguments][1];
  let results = null;
  content = content || window;
  content.fn = this;
  if (args !== undefined) {
    if (!(args instanceof Array)) throw new Error('[...arguments][1] is not a listArray');
    results = content.fn(...args)
  } else {
    results = content.fn()
  }
  delete content.fn
  return results
}

bind

Function.prototype.myBind = function (content: any) {
  if (typeof this !== 'function') {
    throw new Error('is not a function');
  }
  console.log(this);
  const args = [...arguments].slice(1)
  const fn = this as any;
  return function Fn() {
    
    return fn.apply((this) instanceof Fn ? this : content, args.concat(...arguments))
    //(this) instanceof Fn是为了new一个bind的函数需要改变指向
  }
}

\