Perfect solution to the problem that the lower version of IE does not support call and apply

  • 2020-03-30 00:44:02
  • OfStack

Function. Prototype's apply and call were added in 1999 with ECMA262 Edition3 (1998 with ECMA262 Edition2). There was no apply or call in previous browsers such as IE5.01(JScript 5.0). Therefore, there will be some compatibility problems. The following is how to fix it:

if(!Function.prototype.apply){ 
    Function.prototype.apply = function(obj, args){ 
        obj = obj == undefined ? window : Object(obj);//Obj can be a js primitive type
        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); 
    }; 
} 

Related articles: