JS 实现call、apply、bind

83 阅读1分钟

Function.prototype.call()

方法使用一个指定的 this 值和单独给出的一个或多个参数来调用一个函数。

Function.prototype.mycall = function(context) {
    if(typeof this !== 'function') {
        throw new Error('type error')
    }
    let args = [...arguments].slice(1);
    context.fn = this
    let res = context.fn(...args)
    delete context.fn
    return res
}

Function.prototype.apply()

方法调用一个具有给定 this 值的函数,以及以一个数组.

Function.prototype.myapply = function(context,arrArgs) {
    if(typeof this !== 'function' ) {
        throw new Error('type error')
    }
    context = context || global
    context.fn = this
    let res = context.fn(...arrArgs)
    delete context.fn
    return res
}

Function.prototype.bind()

方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。

Function.prototype.mybind = function(context) {
    if(typeof this !== 'function') {
        throw new Error('type error')
    }
    const  args = [...arguments].slice(1)
    const fn = this
    return function Fn() {
        return fn.apply(this instanceof Fn ? this : context, args.concat(...arguments))
    }
}