美文网首页
js call apply bind 源码分析

js call apply bind 源码分析

作者: enheng嗯哼 | 来源:发表于2019-09-26 11:23 被阅读0次

    call 源码分析

    1. 先贴出来源码
    Function.prototype.preCall = function (context) {
        var context = context || window;
        context.fn = this;
    
        var args = [];
        for(var i = 1, len = arguments.length; i < len; i++) {
            args.push('arguments[' + i + ']');
        }
    
        var result = eval('context.fn(' + args +')');
    
        delete context.fn
        return result;
    }
    
    1. 逐句分析

      1.  Function.prototype.preCall = function (context) {} 
        

        我们平常使用的时候会类似这样调用

        function fn() {
          console.log('123')
        }
        fn.call(fn)
        

        所以这里的 context == fn 这个方法

      2.  var context = context || window;
         context.fn = this;
        

        context.fn = this 将 this 赋值给 context.fn 这个属性
        这里的 context.fn === this === fn (这里的 fn 是指外面定义的 function fn() {}),
        第一个很好理解,为何 this === fn(这里的 fn 是指外面定义的 function fn() {})呢 ?
        因为我们在定义 fn 这个方法的时候 fn 的原型是 Function 这个类,那么当我们定义的时候相当于实例化这个方法,在实例化 Function 这个构造函数的时候 会将 this 的指向指定为实例化本体。

      3.   var args = [];
          for(var i = 1, len = arguments.length; i < len; i++) {
              args.push('arguments[' + i + ']');
          }
          var result = eval('context.fn(' + args +')');
          delete context.fn
          return result;
        

        这些就没有什么可说的,前面的 for 循环是为了将实例化的方法存储起来, eval() 这个方法可以运行写在里面的方法 详细可查询 MDN 里面有详细介绍。 最后将运行的结果 return 出去,并将 context.fn 这个属性删除

    2. 分析思考

      1. 为何要写 context.fn = this 这句代码, 能否直接使用 var result = eval('context(' + args +')')?
      2. 如果能,为什么?如果不能,为什么?
        答案肯定是不能的 可以对比一下下面两段代码
      Function.prototype.preCall = function (context) {
          var context = context || window;
          context.fn = this;
          console.log(context.fn)
          console.log(context)
          console.log(context.fn === context)
      
          var args = [];
          for(var i = 1, len = arguments.length; i < len; i++) {
              args.push('arguments[' + i + ']');
          }
      
          var result = eval('context.fn(' + args +')');
      
          delete context
          return result;
      }
      var a = 456
       function fn() {
          var num = 123
          console.log(num)
      }
      var obj = {
          num : 123456,
          logNum: function() {
              console.log(this.num)
          }
      }
      fn.preCall(fn)
      obj.logNum.preCall(fn)
      
      Function.prototype.preCall = function (context) {
      //     var context = context || window;
      //     context.fn = this;
      //  console.log(context.fn)
      //  console.log(context)
      //  console.log(context.fn === context)
      
          var args = [];
          for(var i = 1, len = arguments.length; i < len; i++) {
              args.push('arguments[' + i + ']');
          }
      
          var result = eval('context(' + args +')');
      
          delete context
          return result;
      }
      var a = 456
      function fn() {
          var num = 123
          console.log(num)
      }
      var obj = {
          num : 123456,
          logNum: function() {
              console.log(this.num)
          }
      }
      fn.preCall (fn)
      obj.logNum.preCall (fn)
      

      将结果打印出来就会发现,直接使用 context this 的指向不会发生改变,而我们日常使用的 call 方法会将 this 指向这个方法本身

    apply 源码分析

    Function.prototype.apply = function (context, arr) {
        var context = Object(context) || window;
        context.fn = this;
    
        var result;
        if (!arr) {
            result = context.fn();
        }
        else {
            var args = [];
            for (var i = 0, len = arr.length; i < len; i++) {
                args.push('arr[' + i + ']');
            }
            result = eval('context.fn(' + args + ')')
        }
    
        delete context.fn
        return result;
    }
    

    这里的源码和 call 的源码很类似就不一一解析了

    bind 源码分析

    1. 先贴出来源码
    if (!Function.prototype.bind) {
      Function.prototype.bind = function (oThis) {
        if (typeof this !== "function") {
          throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
        }
    
        var aArgs = Array.prototype.slice.call(arguments, 1), 
            fToBind = this, 
            fNOP = function () {},
            fBound = function () {
              return fToBind.apply(this instanceof fNOP
                                     ? this
                                     : oThis || this,
                                   aArgs.concat(Array.prototype.slice.call(arguments)));
            };
    
        fNOP.prototype = this.prototype;
        fBound.prototype = new fNOP();
    
        return fBound;
      };
    }
    
    1. 逐句分析
    if (!Function.prototype.bind) {
      Function.prototype.bind = function (oThis) {
        // 判断传入的参数是否为 function 如果不是抛出错误并提示
        if (typeof this !== "function") {
          throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
        }
    
        var aArgs = Array.prototype.slice.call(arguments, 1),  // 将 arguments 这个伪数组变成真正的数组,并删除 arguments 中的第一个参数(因为 arguments 的第一个参数为传入的方法本身),这样就得到一个真正的参数数组
            fToBind = this,  // 将传入的方法用变量储存起来,方便调用
            fNOP = function () {},   // 实例化一个新的方法
            fBound = function () {
              // 这里使用了 Function.prototype.apply() 方法
               /*
               * 第一个参数是 function 本身,this instanceof fNOP 判断 this 是否通过new创建的实例,如果是通过new创建的实例,this对象指向新创建的new对象实例
               * 第二个参数是 arguments 数组
               */
              return fToBind.apply(this instanceof fNOP
                                     ? this
                                     : oThis || this, 
                                   aArgs.concat(Array.prototype.slice.call(arguments)));
            };
    
        fNOP.prototype = this.prototype; // 将 bind 的方法本身的 prototype 赋值给新建的构造函数,方便下一步实例化的调用
        fBound.prototype = new fNOP(); // 这里对 fNOP 实例化,防止 this 指向变成 window ,确保 this 的指向指向调用的本体
    
        return fBound; // 将 bind 好的方法返回
      };
    }
    

    相关文章

      网友评论

          本文标题:js call apply bind 源码分析

          本文链接:https://www.haomeiwen.com/subject/vuiiuctx.html