• 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

      

  • 相关阅读:
    Fatal error: Maximum execution time of 30 seconds exceeded in
    常见变量命名规则
    Rust使用国内镜像安装依赖
    flutter使用国内镜像源
    7个每天晚上应该坚持的好习惯
    网络数据传输格式的思考
    Deepin安装 ruby 包管理工具 RVM(适用于 Debian 系列)
    C语言数据类型关键字
    win10 powershell禁止运行脚本解决
    Linux 查看系统相关信息(系统发型版本及内核版本等)
  • 原文地址:https://www.cnblogs.com/johnzhu/p/6510074.html
Copyright © 2020-2023  润新知