JS手写call和apply

call的实现

            Function.prototype.myCall1 = function(context){
                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+')')
                return result;
            }

也可以用ES6的方式:

            Function.prototype.myCall2 = function(context){
                context = context || window
                context.fn = this;
                var args = [];
                for(var i = 1,len = arguments.length; i < len; i++){
                    args.push(arguments[i])
                }
                var result = context.fn(...args);
                delete context.fn
                return result;
            }

apply的实现

            Function.prototype.myApply = function (context,arr){
                var context = context || window;
                context.fn = this;
                if(!arr){
                    result = context.fn()
                }else {
                    var args = [];
                    for(var i = 0, len = arr.length; i 

具体解释请阅读:JavaScript深入之call和apply的模拟实现
转自:https://www.jianshu.com/p/5192aa9f17cc

你可能感兴趣的:(JS手写call和apply)