手写bind、call、apply的最好方式

131 阅读1分钟

采用多种获取原型的方式,多种使用Symbol的方式让你了解他们的使用

手写bind

Function.prototype._bind = function(instance = window) {
  if( instance === null || instance === undefined ) return undefined
  if( typeof instance !== 'object' ) instance = Object.create(Object.getPrototypeOf(instance))

  const fn = Symbol()
  instance[fn] = this

  return (...args) => {
    const res = instance[fn](...args)
    delete instance[fn]
    return res
  }
}

2. 手写一个call

Function.prototype._call = function(instance = window, ...args){
  if( instance === null || instance === undefined ) return undefined
  if( typeof instance !== 'object' ) instance = Object.getPrototypeOf(instance)

  const fn = Symbol('fn')
  instance[fn] = this
  const res = instance[fn](...args)
  delete instance[fn]

  return res
}

3. 手写一个apply

Function.prototype._apply = function(instance = window, args = [] ) {
  if( instance === null || instance === undefined ) return undefined
  if( typeof instance !== 'object' ) instance = instance.__proto__

  instance[Symbol.for('fn')] = this
  const res = instance[Symbol.for('fn')](...args)
  delete instance[Symbol.for('fn')]

  return res 
}

点击获取更多手写题