weijiyang / GOOD-IDEA

这里记录一些灵感~详见ISSUES
1 stars 0 forks source link

手写call apply bind函数 #9

Open weijiyang opened 5 years ago

weijiyang commented 5 years ago
Function.prototype.call = function (context) {
  let ctx = context || window 
  ctx.func = this // 将该函数赋值给ctx.func this指针调整
  let args = Array.from(arguments.slice(1))
  return args.length > 0 ? ctx.func(...args) : ctx.func()
}
weijiyang commented 5 years ago
Function.prototype.apply = function (context) {
  let ctx = context || window
  ctx.func = this
  return argument.length > 1 ? ctx.func(arguments[1]) : ctx.func()
}
weijiyang commented 5 years ago
Function.prototype.bind = function (context) {
  let ctx = context || window
  ctx.func = this
  let args = Array.from(arguments.slice(1))
  return function () {
    let param = args.concat(...arguments)
    let res = param.length ? ctx.func(param) : ctx.func()
    delete ctx.func
    return res
  }
}

注意:

  1. 初始遗漏了param为空的情况
  2. 这里context赋值需要进行深拷贝or 删除ctx.func 防止将值付给context