手写常规代码总结

手写 call

// func.call(this, a, b)
Object.prototype._call = function(context, ...params){
    if(typeof this !== 'function'){
        throw TypeError('type is fail')
    }
    let that = context || window
    let symbol = Symbol('func')
    that[symbol] = this
    let result = that[symbol](...params)
    delete that[symbol]
    return result
}

手写 apply

// func.apply(this, [a, b])
Object.prototype._apply = function(context, params = []){
    if(typeof this !== 'function'){
        throw TypeError('type is fail')
    }
    let that = context || window
    let symbol = Symbol('func')
    that[symbol] = this
    let result = that[symbol](...params)
    delete that[symbol]
    return result
}

手写 bind

// func.bind(this, a, b)
Object.prototype._bind = function(context, ...params1){
    if(typeof this !== 'function'){
        throw TypeError('type is fail')
    }
    let that = context || window
    return (...params2) => {
        this.call(that, ...params1,)
    }
}

手写 instanceof

function instanceof(L, R){
    let l = L._proto_
    let r = R.prototype
    while(true){
        if(l === null) return false
        if(l === r) return true
        l = l._proto_
    }
}