重写apply、call、bind方法

53 阅读1分钟
Function.prototype.myApply = function(ctx, params) {
    ctx = ctx ? Object(ctx) : window
    let f = Symbol()
    ctx[f] = this
    ctx[f](...params)
    delete ctx[f]
}
Function.prototype.myCall = function(ctx, ...params) {
    ctx = ctx ? Object(ctx) : window
    let f = Symbol()
    ctx[f] = this
    ctx[f](...params)
    delete ctx[f]
}
Function.prototype.myBind = function(ctx, ...params) {
    ctx = ctx ? Object(ctx) : window
    let f = Symbol()
    ctx[f] = this
    return (...params_) => {
        const result = ctx[f](...params, ...params_)
        delete ctx[f]
        return result
    }
}