手写call、apply、bind函数

105 阅读1分钟
/**
    # call
    self: 要绑定的this
    xx.call(): 隐式绑定,this指向xx,这里刚好为fn函数
    剩余参数和扩展参数形式虽一样,但含义不同
*/
Function.prototype.myCall = function(self, ...args) { 
    let fn = this
    self = self ? Object(self) : window
    self.fn = fn
    let result = self.fn(...args)
    delete self.fn
    return result
}

/**
    # apply
    与call唯一不同的是传参,直接传一个数组
*/
Function.prototype.myApply = function(self, args) { 
    let fn = this
    self = (self !== null && self !== undefined) ? Object(self) : window
    self.fn = fn
    args = args || []                //逻辑或、三元运算符、if均可判断
    let result = self.fn(...args)
    delete self.fn
    return result
}

/**
    # bind
*/
Funtion.prototype.myBind = function(self, ...args1) {
    let fn = this
    self = (self !== null && self !== undefined) ? Object(self) : window
    return funtion(...args2) {
        self.fn = fn
        args = [...args1, ...args2]             //也可数组concat
        let result = self.fn(...args)
        delete self.fn
        return result
    }
}