zoukankan      html  css  js  c++  java
  • ES3实现apply,call,bind方法

      IE5之前没有apply和call的支持,下面的方法兼容版本IE

    if(!Function.prototype.apply){ 
        Function.prototype.apply = function(obj, args){ 
            obj = obj == undefined ? window : Object(obj);//obj可以是js基本类型 
            var i = 0, ary = [], str; 
            if(args){ 
                for( len=args.length; i<len; i++ ){ 
                    ary[i] = "args[" + i + "]"; 
                } 
            } 
            obj._apply = this; 
            str = 'obj._apply(' + ary.join(',') + ')'; 
            try{ 
                return eval(str); 
            }catch(e){ 
            }finally{ 
                delete obj._apply; 
            }    
        }; 
    } 
    if(!Function.prototype.call){ 
        Function.prototype.call = function(obj){ 
            var i = 1, args = []; 
            for( len=arguments.length; i<len; i++ ){ 
                args[i-1] = arguments[i]; 
            } 
            return this.apply(obj, args); 
        }; 
    } 
    
    Function.prototype.es3Bind = function (context) {
      if (typeof this !== "function") throw new TypeError('what is trying to be bound is not callback');
      var self = this;
      var args = Array.prototype.slice.call(arguments, 1);
      const fBound = function () {
        // 获取函数的参数
        var bindArgs = Array.prototype.slice.call(arguments);
        // 返回函数的执行结果
        // 判断函数是作为构造函数还是普通函数
        // 构造函数this instanceof fNOP返回true,将绑定函数的this指向该实例,可以让实例获得来自绑定函数的值。
        // 当作为普通函数时,this 指向 window,此时结果为 false,将绑定函数的 this 指向 context
        return self.apply(this instanceof fNOP ? this: context, args.concat(bindArgs));
      }
      // 创建空函数
      var fNOP = function () {};
      // fNOP函数的prototype为绑定函数的prototype
      fNOP.prototype = this.prototype;
      // 返回函数的prototype等于fNOP函数的实例实现继承
      fBound.prototype = new fNOP();
      // 以上三句相当于Object.create(this.prototype)
      return fBound;
    }

    //test

    function test(a,b){
    var re = this.x+a+b
    console.log(re)
    }

    var f = test.bind({x:3},3);
    f(5) //11=3+3+5

     

    参考链接: https://blog.csdn.net/u010377383/article/details/80646415

      

  • 相关阅读:
    【CentOS】CentOS7开放及查看端口
    【nginx】配置https 证书生成的方法
    【MacOs】 Royal TSX SSH 和 FTP 中文乱码
    【PHP】thinkphp3.2.5
    【TCP/IP】入门学习笔记 五
    【TCP/IP】入门学习笔记 四
    HTTP
    【PHP】高并发和大流量的解决方案(思路)
    react多级路由 重定向与404定义
    react自定义导航组件 路由参数
  • 原文地址:https://www.cnblogs.com/johnzhu/p/6510074.html
Copyright © 2011-2022 走看看