相同点:都是改变this的指向问题
区别
接收的参数的个数不一样
- call(thisObj,arg1, arg2, ,.argN) 可以接手多个参数,第一个参数是this要指向的对象
- apply([thisObj,argArray) 接收两个参数,第二个使用数组的格式
- bind方法的返回值是函数,参数和call一样,可以多个 ,但是bind不会立即执行该函数,因为它本身是一个函数,需要调用它bind()()
源码实现(在一次面试中,第一题就是myCall的源码,而我在这里跌倒☹️)
call实现:
Function.prototype.mycall = function (context) {
// 当context为null时,其值则为window
context = context || window;
// this为调用mycall的函数。将this赋值给context的fn属性
context.fn = this;
// 将arguments转为数组,并从下标1位置开如截取
let arg = [...arguments].slice(1);
// 将arg数组的元素作为fn方法的参数执行,结果赋值给result
let result = context.fn(...arg);
// 删除fn属性
delete context.fn;
// 返回结果
return result;
}
apply实现:
Function.prototype.myapply = function (context) {
// 当context为null时,其值则为window
context = context || window
// this为调用myapply的函数。将this赋值给context的fn属性
context.fn = this;
// 如果未传值,则为一空数组
let arg = arguments[1] || [];
// 将arg数组的元素作为fn方法的参数执行,结果赋值给result
let result = context.fn(...arg);
// 删除fn属性
delete context.fn
// 返回结果
return result
}
bind实现:
Function.prototype.mybind = function (context) {
// this为调用mybind的函数。将this赋值给变量_this
let _this = this;
// 将arguments转为数组,并从下标1位置开如截取
let arg = [...arguments].slice(1);
// 返回函数fn
return function fn(){
// 通过apply方法调用函数并返回结果。
return _this.apply(context, arg.concat(...arguments));
}
}