call和apply的区别
介绍:
每个函数都包含两个非继承而来的方法:call()
和apply()
;
call与apply都属于Function.prototype的一个方法,所以每个function实例都有call、apply属性;
1.相同点:改变this的指向。
2.区别:传值的方式不一样。
call(obj,arg1,arg2,arg3) 通过调用call 方法,在传第一个参数的时候,函数里的this指向第一个参数。从第二参数起依次传入给函数的参数值。
apply(obj,args)调用 apply方法,第一个参数同call一样,是函数里this指向第一个参数,第二个参数为数组。此方法会遍历传入参数的值。
Call实现方法:
过程思考:1.首先是所有的函数都可以调用call,说明call是函数原型上的方法,所有实例都可以调用,即function.prototype.call.
1.1:在call方法里获取调用call()函数。
1.2如果第一个参数没有传入,那么默认指向window/global
1.3传入的call的第一个参数是this指向的对象,根据隐式绑定的规则。我们知道obj.foo(),foo()中的this指向obj;因此我们可以obj.func(...args)
1.4执行返回结果。
上代码:
Function.prototype.call = function(){
let [thisArg,...args]=[...arguments];
if(!thisArg){
thisArg = typeof window === 'undefined' ? global : window;
}
thisArg.func = this;
let result = thisArg.func(...args);
delete thisArg.func;
return result;
}
apply的实现方法:
Function.prototype.apply = function(thisArg,rest){
let result;
if(!thisArg){
thisArg= typeof window === 'undefined'? global:window;
}
thisArg.func = this;
if(!rest){
result = thisArg.func();
}else{
result = thisArg.func(...rest);
}
delete thisArg.func;
return result;
}
* 参考公众号前端宇宙 (这儿有20道大厂面试题等你查收)