改变this指向的三种手写

// eslint-disable-next-line no-extend-native
Function.prototype.myCall = function (...args) {
    const target = args[0]
    target._f = this
    target._f(...args.slice(1))
    delete target._f
}

// eslint-disable-next-line no-extend-native
Function.prototype.myApply = function (...args) {
    const target = args[0]
    target._f = this
    target._f(...args[1])
    delete target._f
}

// eslint-disable-next-line no-extend-native
Function.prototype.myBind = function (...args) {
    const target = args[0]
    target._f = this
    return () => {
        target._f(...args.slice(1))
        delete target._f
    }
}

alice.say.call(bob, 'haha', 'fem')
alice.say.myCall(bob, 'haha', 'fem')
alice.say.apply(bob, ['hhh', 'asdasd'])
alice.say.myApply(bob, ['hhh', 'asdasd'])
alice.say.bind(bob, 'hhh', 'asdasd')()
alice.say.myBind(bob, 'hhh', 'asdasd')()

  

posted on 2021-10-14 10:23  hhvfg  阅读(48)  评论(0)    收藏  举报