欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

手写call,apply,bind实现

程序员文章站 2022-03-08 09:44:09
...

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

call实现

    Function.prototype._call = function (context) {
      var context = context || window; 
      context._fn_ = this;
      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);
      }
    }
复制代码

转载于:https://juejin.im/post/5d47b164f265da03f47c0604