自定义call方法和apply方法

call方法

/*
    call(Fn,obj,...args)
    Fn为要执行的函数   obj是this指向的对象   ...args是形参
*/

function call(Fn,obj,...args){
    //判断obj对象是否存在
    if(obj === undefined || obj === null){
        obj = globalThis
    }
    //为obj添加临时方法
    obj.temp = Fn
    //调用temp方法
    let result = obj.temp(...args)
    //删除temp方法
    delete obj.temp
    //返回执行结果
    return result
}

apply方法

/*
    apply(Fn,obj,args)
    Fn:要执行的函数   obj:this指向的对象    args:形参组成的数组
*/
function apply(Fn,obj,args){
    //判断obj是否存在
    if(obj == undefined || obj == null){
        obj = globalThis
    }
    //为obj添加临时方法
    obj.temp = Fn
    //执行临时方法
    let result = obj.temp(...args)
    //删除临时方法
    delete obj.temp
    //返回结果
    return result
}

bind方法返回的是一个函数 先传入的参数有效,后传入的参数无效

function call(Fn,obj,...args){
    if(obj == undefined || obj == null)
        obj = globalThis
    obj.temp = Fn
    let result = obj.temp(...args)
    delete obj.temp
    return result 
}
/*
    bind返回的是一个函数
例:
    let fn = add.bind(obj,10,20)    
    console.log(fn(30,40))     先传入的参数为10和20,后面传入的30,40不起作用
*/
function bind(Fn,obj,...args) {
    return function (...args2){
        return call(Fn,obj,...args,...args2)
    }
}
function add(a,b){
    return a+b+this.c
}
let obj = {
    c:521
}

let fn3 = bind(add,obj,10,20)
console.log(fn3(30,40))
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值