js实现bind

之前在各大网站找到的方法都是直接调用原生call,但是调用原生就失去了我们自己实现bind的初衷,所以这里就顺便把call也一并实现
整个过程尽量使用基础操作,比起网上的简单版代码比较多,需要耐心
先准备初始数据

  const obj1 = {
    name: 'ha',
  };
  function getName() {
    // 直接执行必然输出undefined
    console.log(this.name);
  }

接下来实现bind

  Function.prototype._bind = function() {
    const beBind = this,
      obj = arguments[0],
      args = [];
    for (let i = 1; i < arguments.length; i++) {
      // 我们可以自己实现一个_push方法,通过遍历作出一个数组,实现方法在本文最后
      args._push(arguments[i]); 
    // 如果不想自己实现数组push方法,可以使用args = Array.prototype.slice.call(arguments, 0)替代上一行代码
    }
    if (typeof beBind === 'function') {
      return function() {
        beBind._call(obj, args);
      };
    } else {
      throw new Error("can't be bind");
    }
  };

要点说明:
1.arguments 为function内部实现的参数,存在于任何一个function中,包含所有传入的参数
2.arguments为数组形式的object,却并没有继承自Array,无法进行各种Array的操作,但可以遍历

  1. 遍历时 i 初始值为1是为了舍去arguments[0],因为在上面已经被赋值给obj,剩下的才是我们需要的参数

因为在bind中调用了_call,所以我们再实现一个_call

  Function.prototype._call = function() {
    if (typeof arguments[0] === 'object') {
      const obj = {},
        args = [];
      for (let i = 1; i < arguments.length; i++) {
        args._push(arguments[i]);
      }
      for (const key in arguments[0]) {
        const item = arguments[0][key];
        obj[key] = item;
      } 
// 这一步遍历只是为了浅拷贝,当然,不考虑兼容等其他因素,可以使用扩展运算符... 与 Object.assign()
      obj['_beCall'] = this;
      obj._beCall(args); 
// 上面的浅拷贝就是为了创建_beCall,而又不必delete它,并且也不需要考虑_beCall已存在而被覆盖的问题,对象delete性能慢,并且在某些环境下,会产生无法预知的错误
    }
  };

因为在bind中调用了_push,我们再实现一个_push以供使用

  Array.prototype._push = function() {
    this[this.length] = arguments[0];
  };

最后查看效果

  getName._call(obj1);
  const newFun = getName._bind(obj1);
  newFun();
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。