实现call-apply-bind

71次阅读

共计 790 个字符,预计需要花费 2 分钟才能阅读完成。


// 手写实现 call
Function.prototype.mCall = function(context) {
  const ctx = context || window
  ctx.func = this
  const args = Array.from(arguments).slice(1)
  const res = arguments.length > 1 ? ctx.func(...args) : ctx.func()
  delete ctx.func
  return res
}

Function.prototype.mApply = function(context) {
  const ctx = context || window
  ctx.func = this
  const res = arguments[1]? ctx.func(...arguments[1]) : ctx.func()
  delete ctx.func
  return res
}

Function.prototype.mBind = function(context) {const ctx = JSON.parse(JSON.stringify(context)) || window
  ctx.func = this
  const args = Array.from(arguments).slice(1)
  return function() {const Allargs = args.concat(Array.from(arguments))
    return Allargs.length>0?ctx.func(...Allargs): ctx.func;
  }
}
const obj =  {getName: function() {console.log('原始。。。', this.name)
  }
}
const nowObj = {name: 'js'}

// obj.getName.call(nowObj)
obj.getName.bind(nowObj)
console.log(obj)

正文完
 0