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 <len; i++){
args.push('arr['+i+']');
}
result = eval('context.fn('+args+')')
}
delete context.fn;
return result;
}
具体解释请阅读:JavaScript深入之call和apply的模拟实现