跳至主要內容

实现 Function 的原生方法

haneball大约 1 分钟JavaScriptTypeScript原生方法

bind 方法

  • 参数有 thisArg 和原函数的参数 args
  • thisArgundefined,则赋值全局对象 window
  • 支持衔接后续传入的参数 otherArgs
interface Function {
    myBind(thisArg: any, ...args: any[]): any
}

Object.defineProperty(Function.prototype, 'myBind', {
    enumerable: false,
    writable: false,
    configurable: false,
    value: function myBind(this: Function, thisArg: any, ...args: any[]): any {
        const _self = this
        thisArg = thisArg || window

        return function(...otherArgs: any[]) {
            return _self.apply(thisArg, args.concat(otherArgs))
        }
    }
})

call 方法

  • 参数有 thisArg 和原函数的其他参数 args
  • thisArgundefined,则赋值全局对象 window
interface Function {
    myCall(thisArg: any, ...args: any[]): any
}

Object.defineProperty(Function.prototype, 'myCall', {
    enumerable: false,
    writable: false,
    configurable: false,
    value: function myCall(this: Function, thisArg: any, ...args: any[]): any {
        thisArg = thisArg || window
        thisArg._fn = this

        const result = thisArg._fn(...args)
        delete thisArg._fn

        return result
    }
})

apply 方法

  • 参数有 thisArg 和原函数的参数数组 args
  • thisArgundefined,则赋值全局对象 window
interface Function {
    myApply(thisArg: any, args?: any[]): any
}

Object.defineProperty(Function.prototype, 'myApply', {
    enumerable: false,
    writable: false,
    configurable: false,
    value: function myApply(this: Function, thisArg: any, args?: any[]): any {
        let result: unknown
        thisArg = thisArg || window
        thisArg._fn = this

        if (args) {
            result = thisArg._fn(...args)
        } else {
            result = thisArg._fn()
        }

        delete thisArg._fn

        return result
    }
})