JS基础,实现 call、apply、bind 方法

139 阅读1分钟

一、call

实现

const callFactory = function (context){
    context = context || window
    
    const symbol = Symbol()
    context[symbol] = this

    const args = Array.prototype.slice.call(arguments, 1)
    const fn = context[symbol](...args)

    delete context[symbol]
    return fn
}

验证

image.png

二、apply

实现

const applyFactory = function (context){
    context = context || window

    const symbol = Symbol()
    context[symbol] = this

    const args = Array.prototype.slice.call(arguments, 1).shift()
    const fn = context[symbol](...args)

    delete context[symbol]
    return fn
}

验证

image.png

三、bind

注意

  • bind 这里有一个需要注意的点,如果将 bind 函数的返回值,实例化成一个对象,bind 时指定的值会失效,但传入的参数依然生效

image.png

实现

const bindFactory = function (context){
    context = context || window

    let _this = this
    let args = Array.prototype.slice.call(arguments, 1)

    return function foundB() {
        let bindArgs = Array.from(arguments)
        return _this.apply(this instanceof foundB ? this : context, args.concat(bindArgs))
    }
}

验证

image.png