call、bind、apply都是改变当前this指向的问题,但各自有各自的区别
call
call函数接收两个多个参数,第一个是当前this的指向是水,其他的就是为改变指向的方法所传的参数。修改当前指向的时候也会执行对应的函数
function add(a,b){
...
}
add.call(this,2,3);//2指add中参数a,3指的是参数b;这里的this应该是window
call的实现
Function.prototype.call=function(content=window){
content.fn=this;
let args=[...arguments].slice(1);
let result=content.fn(...args);
delete content.fn
return result
}
apply
apply也call相似,但apply接收的是一个数组;
function add(a,b){
...
}
add.apply(this,[1,2])
apply的实现
Function.protptype.apply=function(content=window){
content.fn=this;
let result;
if(argments[1]){
result=content.fn(...argmengts[1])
}else{
result=content.fn();
}
delete content.fn;
return result
}
bind
会创建一个新函数。当这个新函数被调用时,bind() 的第一个参数将作为它运行时的 this,之后的一序列参数将会在传递的实参前传入作为它的参数。(来自于 MDN )
function add(a,b){
...
}
var Add=add.bind(this,[1,2])
bind的实现
Function.protype.bind=function(content){
if(content instanceof Function){
let _this=this;
let args=[...arguments].slice(1);
return function Fn(){
if(this instanceof Fn){
return _this.apply(this,args.concat([...arguments]))
}
return _this.apply(content,args.concat([...arguments]))
}
}else{
throw Error('not a function')
}
}