apply - call - bind实现

120 阅读2分钟

关于apply和call

这两个方法其实可以用来实现函数的调用 这两个方法的调用其实会将一个 {} 空对象传入函数执行上下文 期中这个地址指向的就是这个函数

如果想要对变量key的类型进行限制可以使用

🍔call函数实现

const num = Object(123)

这样的话就会变成一个对象类型 如果Object后的括号里面是对象的话 Object()调用之后还会是一个对西昂

//给所有函数添加一个hycall方法 参数除了 还有一个 restparameters --> ...args
//获取到需要被执行的函数
//将参数转换成对象类型 防止传入的值为非对象类型 同意防止传入的是 null 或者 undefined
//调用被执行的函数
//取到结果并返回
Function.prototype.hycall = function(thisArg, ...args) {
    const fn = this
    thisArg = thisArg ? Object(thisArg) : window
    thisArg.fn = fn
    const result = thisArg.fn(...args)
    delete thisArg.fn
    return result
}

对于一个函数是否要写return取决于函数外部有没有调用到这个结果

🍔apply函数实现

关于 apply 跟 call 的区别就是在参数这边 call 函数除了对象以外还可以有很多个参数 但是 apply 的话就要传入一个数组 将其他的参数放进去 这样的话就可能会出现没有传参数的情况 如果没有传参数的话 ...args 就相当于是 ...undefined 这样的话就会报错 所以我们需要在 hyapply 里面进行一个判断

Function.prototype.hyapply = function(thisArg, argArray) {
    const fn = this
    thisArg = (thisArg === null || thisArg === undefined) ? Object(thisArg) : window
    thisArg.fn = fn
    var result
    
    argArray = argArray ? argArray : []
    result = thisArg.fn(...argArray)
    
    delete thisArg.fn
    
    return result
}

🍔bind函数实现

Function.prototype.hybind = function(thisArg, ...argArray) {
    var fn = this
    thisArg = (thisArg !== null && thisArg !== undefined) ? Object(thisArg) : window
    
    function proxyFn(...args) {
        thisArg.fn
        var finalArgs = [...argArray, ...args]
    }
}

未完待续 先了解一下这三个函数 剩下的再说 目前看到了1:50:00

\