call apply bind的区别

相同点:都是改变this的指向问题

区别

接收的参数的个数不一样

  1. call(thisObj,arg1, arg2, ,.argN) 可以接手多个参数,第一个参数是this要指向的对象
  2. apply([thisObj,argArray) 接收两个参数,第二个使用数组的格式
  3. 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));
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值