apply,call,bind实现原理

apply:方法能劫持另外一个对象的方法,继承另外一个对象的属性.

Function.apply(obj,args)方法能接收两个参数

obj:这个对象将代替Function类里this对象

args:这个是数组,它将作为参数传给Function(args–>arguments)

Function.prototype.apply = function(thisArg=window ){
    if (typeof this !== 'function') { // 调用call的若不是函数则报错
        throw new TypeError('Error');
    }
    thisArg.fn = this;//将调用apply函数的对象添加到thisArg的属性中。
    let result;
    if(arguments[1]){					//如果有第二个参数,添加进去
        result = thisArg.fn(arguments[1]);
    }else{
        result = thisArg.fn();
    }
    delete thisArg.fn;
    return result;
}

call:和apply的意思一样,只不过是参数列表不一样.

Function.call(obj,[param1[,param2[,…[,paramN]]]])
obj:这个对象将代替Function类里this对象
params:这个是一个参数列表

Function.prototype.call = function(thisArg=window ,...arg){
    if (typeof this !== 'function') { // 调用call的若不是函数则报错
        throw new TypeError('Error');
    }
    thisArg.fn = this;//将调用apply函数的对象添加到thisArg的属性中。
    const result = thisArg.fn(...arg);
    delete thisArg.fn;
    return result;
}

bind方法会创建一个新函数,当这个新函数被调用时,bind()的第一个参数将作为他运行时的this,后面参数为多个,不是数组。

Function.prototype.bind = function(thisArg,...args ){
    if (typeof this !== 'function') { // 调用call的若不是函数则报错
        throw new TypeError('Error');
    }
    let _this = this;//存储函数本身
    let args = [...arg]; //提取后面的参数
    return function F(){
        if(this instanceof F){ //可能是一个构造函数
            return _this.apply(this,args.concat([...arguments]));
        }
        return _this.apply(thisArg,args.concat([...arguments]));
    }
   
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值