call
call()方法在使用一个指定的this值和若干个指定的参数值的前提下调用某个函数或方法
Function.prototype.call=function(context) {
context=context || Window;
context.fn=this;
let args=[];
for(let i=1;i<arguments.length;i++) {
args.push("arguments["+i+"]");
}
let result = eval('context.fn('+args+')');
delete context.fn;
return result;
}
apply
Function.prototype.apply=function(context,arr){
context=context || window;
context.fn=this;
let result;
if(!arr) {
result = context.fn();
}else {
let args=[];
for(let i = 0;i<arr.length;i++) {
args.push('arr['+i+']');
}
result=eval('context.fn('+args+')');
}
delete context.fn;
return result
}
bind
bind()方法创建一个新函数。当这个新函数被调用时,bind()的第一参数将作为它运行时的this,之后的一序列参数将会在传递的实参前传入作为它的参数。新函数也能使用new操作符创建对象:这种行为就像把原函数当成构造器。提供的this值被忽略,同时调用时的参数被提供给模拟函数
Function.prototype.bind=function(context) {
if(typeof this !== 'function') {
throw new Error("必须要是函数哦")
}
let self =this;
let args = Array.prototype.slice.call(arguments,1);
let fNOP= function (){};
let fBound = function(){
let boundArgs=Array.prototype.slice.call(arguments);
return self.apply(this instanceof fNOP?this:context,args.concat(boundArgs))
}
fNOP.prototype=this.prototype;
fBound.prototype=new fNOP();
return fBound
}