手写JS(三)--实现call apply bind

452 阅读1分钟
Function.prototype.myCall = function(context) {
  context.temp = this;
  const args = [...arguments].slice(1);
  const res = context.temp(...args);
  delete context.temp;
  return res;
}

Function.prototype.myApply = function(context) {
  context.temp = this;
  const args = [...arguments][1];
  const res = context.temp(...args);
  delete context.temp;
  return res;
}

Function.prototype.myBind = function(context) {
  const me = this; // 这个this指向的是myBind的调用者
  const args = [...arguments].slice(1);
  return function Result() {
    // myBind最后return了Result方法,但是没有运行,这里的this指向运行时的环境
    if(this instanceof Result) {
      // Result可能被当做构造函数来使用
      // 兼容使用new来创建Result实例
      // 既可以在myBind调用时传参,也可以实例化的时候传参
      return new me(...args, ...arguments);
    }
    return me.apply(context, args.concat(...arguments));
  }
}