美文网首页
call/apply/bind

call/apply/bind

作者: jiangzj | 来源:发表于2019-02-23 19:40 被阅读0次
// func.geCall(obj, 'arg1', 'arg2')
Function.prototype.geCall = function (context) {
  var context = context || window
  // 给 context 添加一个函数
  context.fn = this
  // 将 context 后面的参数取出来
  var args = [...arguments].slice(1)
  var result = context.fn(...args)
  // 删除 fn
  delete context.fn
  return result
}

// func.geApply(obj, ['arg1', 'arg2'])
Function.prototype.geApply = function (context) {
  var context = context || window
  context.fn = this

  var result

  if (arguments[1]) {
    result = context.fn(...arguments[1])
  } else {
    result = context.fn()
  }

  delete context.fn
  return result
}

Function.prototype.geBind = function(context){
  let _this = this
  let args = [...arguments].slice(1)
  const fn = function() {
    return _this.apply(context, [...args, ...arguments])
  }
  return fn
}

相关文章

网友评论

      本文标题:call/apply/bind

      本文链接:https://www.haomeiwen.com/subject/uuapyqtx.html