手写call,apply,bind实现

254 阅读1分钟

call,apply,bind函数其本质是实现改变函数上下文环境,即改变this

call实现

    Function.prototype._call = function (context) {
      var context = context || window; 
      context._fn_ = this; //this指向_call函数调用者
      var [_this, ...args] = arguments
      var result = context._fn_(...args)
      delete context._fn_;
      return result; //可能this函数会有返回值
    }

apply实现

    Function.prototype._apply = function (context) {
      var context = context || window;
      context._fn_ = this;
      var [_this, args] = arguments //需要校验args为数组
      console.log('args :', args);
      var result = context._fn_(...args)
      delete context._fn_;
      return result;
    }

bind实现

借助apply实现
    Function.prototype._bind = function (context, ...args) {
      return () => {
        this.apply((context || window), args)
      }
    }
纯原生实现
    Function.prototype._bind2 = function (context=window, ...args) {
      context._fn_ = this
      return () => {
        context._fn_(...args);
      }
    }