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

  

相关文章:

  • 2021-07-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-03
  • 2021-12-31
  • 2021-09-21
  • 2021-07-11
猜你喜欢
  • 2021-06-19
  • 2022-12-23
  • 2022-12-23
  • 2022-01-26
  • 2021-07-06
  • 2022-12-23
  • 2021-08-30
相关资源
相似解决方案