简单使用js 模拟call、apply、bind

107 阅读1分钟
  1. _call
    Function.prototype._call = function(thisBind, ...args) {
        thisBind = thisBind ? Object(thisBind) : window
        thisBind.fn = this
        let result = thisBind.fn(...args)
        delete thisBind.fn
        return result
    }
  1. _apply
    Function.prototype._apply = function(thisBind, arg) {
        thisBind = thisBind ? Object(thisBind) : window
        thisBind.fn = this
        let result = undefined
        if (arg === undefined) {
            result = thisBind.fn()
        } else {
            result = thisBind.fn(...arg)
        }
        delete thisBind.fn
        return result
    }

3._bind

    Function.prototype._bind = function(thisBind, ...args) {
        thisBind = thisBind ? Object(thisBind) : window
        thisBind.fn = this
        return function(...newArgs) {
            let finalArgs = [...args, ...newArgs]
            return thisBind.fn(...finalArgs)
        }
    }