手写apply-call-bind

apply

// thisArg指向传入的对象
// function内this隐式绑定:this指向调用myApply的函数

Function.prototype._apply = function(thisArg,args){
    // 非严格模式下,传入null或undefined thisArg指向window
    // 其他转化为包装类型
    thisArg = (thisArg === null || thisArg === undefined) ? window : Object(thisArg)

    thisArg.fn = this

    // 调用函数后的返回值
    const res = thisArg.fn(...args)
    delete thisArg.fn
    return res
} 

call

// thisArg指向传入的对象
// function内this隐式绑定:this指向调用myApply的函数

Function.prototype._call = function(thisArg,...args){
    // 非严格模式下,传入null或undefined thisArg指向window
    // 其他转化为包装类型
    thisArg = (thisArg === null || thisArg === undefined) ? window : Object(thisArg)

    thisArg.fn = this

    // 调用函数后的返回值
    const res = thisArg.fn(...args)
    delete thisArg.fn
    return res
} 

bind

返回值:返回一个原函数的拷贝,并拥有指定的 this 值和初始参数。

// thisArg指向传入的对象
// function内this隐式绑定:this指向调用myApply的函数

Function.prototype._bind = function (thisArg, ...args1) {
    // 非严格模式下,传入null或undefined thisArg指向window
    // 其他转化为包装类型
    thisArg = (thisArg === null || thisArg === undefined) ? window : Object(thisArg)

    thisArg.fn = this

    // 返回一个函数
    // 该函数接收剩余的参数,参数合并后执行
    return (...args2) => {
        thisArg.fn(...[...args1, ...args2])
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值