call、apply、bind实现原理
call实现原理
Function.prototype.call = function () { var ctx = arguments[0] || window;
ctx.fn = this;
var args = [];
for(let i = 0; i < arguments.length; i++){
args.push("arguments['+i+']")
}
var result = eval("ctx.fn('+args.join(',')+')");
delete ctx.fn;
return result
}
apply实现原理
Function.prototype.apply = function (ctx,arr) { ctx = ctx || window;
ctx.fn = this;
if(!arr) {
var result = ctx.fn()
delete ctx.fn;
return result;
}else{
var args = [];
for(var i = 0; i < arr.length; i++){
args.push("arr['+i+']")
}
var result = eval("ctx.fn('+args.join(',')+')")
delete ctx.fn
return result
}
}
bind实现原理
Function.prototype.bind = function (target) { target = target || window;
var self = this;
var args = [].slice.call(arguments,1)
var temp = function(){}
var F = function () {
var arg = [].slice.call(arguments,0);
return self.apply(self instanceof temp ? self:target,arg.concat(args))
}
temp.prototype = self.prototype
F.prototype = new temp()
return F
}

浙公网安备 33010602011771号