JavaScript高级之手写apply-bind

56 阅读1分钟

什么是apply?

官方: apply() 方法调用一个具有给定 this 值的函数,以及以一个数组(或一个类数组对象)的形式提供的参数。

我的理解:绑定this,并且参数是以数组的形式传入

实现

Function.prototype.xyapply = function (thisArg, argArray) {
    let fn = this
    thisArg = thisArg ? Object(thisArg) : window
    thisArg.fn = fn
    let result
    if (argArray) {
      result =  thisArg.fn()
    } else {
      result =  thisArg.fn(...argArray)
    }
    delete thisArg.fn
    return result
}

bind也类似的就不额外解释了

实现

Function.prototype.xybind = function (thisArg, ...argArray) {
    let fn = this
    thisArg = thisArg ? Object(thisArg) : window

    return function (...args) {
        thisArg.fn = fn

        let result = thisArg.fn(...argArray, ...args)
        delete thisArg.fn
        return result
    }
}

function sum(num1, num2) {
    console.log('sum 被调用', this, num1, num2,arguments)
}

sum() // window
sum.bind('bind', 20, 30)
let res = sum.xybind('xybind', 20)
res(30, 40)