call,apply,bind 实现

正文

Tips:call bind apply对箭头函数来说,会忽略掉第一个参数,也就是this指向参数,所以不会改变箭头函数this的指向

  • call实现
    1. this指向绑定
    2. 传参
    3. 返回值,看了很多的实现例子,都没有写这个。如果缺少返回值,那么对很多函数的模拟实现call就不会成功,尤其是函数具有返回值的时候,比如Object.prototype.toString.call()
    4. thisArgnull或者undefined时,会指向全局对象
Function.prototype.myCall = function (thisArg) {
    const globalObj = typeof window === 'undefined' ? global : window
    thisArg = thisArg ? thisArg : globalObj

    thisArg[this.name] = this

    const args = [...arguments].slice(1)
    const val = thisArg[this.name](...args)

    delete thisArg[this.name]
    return val
}
  • apply
    • 相比call来说,唯一的不同点就是传给原函数的参数类型是数组或是伪数组或是其它可转化为数组的数据类型
Function.prototype.myApply = function (thisArg, argsArr) {
    if (typeof argsArr !== 'object') {
        throw new Error('CreateListFromArrayLike called on non-object')
    }

    const globalObj = typeof window === 'undefined' ? global : window

    thisArg = thisArg ? thisArg : globalObj
    thisArg[this.name] = this
    console.log(Array.from(argsArr))
    const val = thisArg[this.name](...Array.from(argsArr))

    delete thisArg[this.name]
    return val
}
  • bind实现
    • 函数的柯里化

    • const fn = this要在返回函数的外侧保存一下this,不然返回函数内部this指向为全局对象

    • 在这里不用判断thisArg是否为空,因为之后会调用apply,它会处理的

    • bind关于new的特性,待补充(懒)

Function.prototype.myBind = function (thisArg) {
    const args = [].splice.call(arguments, 1)
    const fn = this
    return function () {
        fn.apply(thisArg, [...args, ...arguments])
    }
}

结语

如果对你有帮助的话,请点一个赞吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值