手写bind, call, apply

95 阅读1分钟
bind
  1. 返回的是一个函数
  2. 先拿到被 bind 的 function
  3. customBind 的挷定的参数和后传的参数并,用 apply 在 context 上应用
Funtion.prototype.customBind = function(context, ...args){
   const self = this
    return function(){
      self.apply(context, [...args, ...arguments])
    }
}
call
  1. customCall调用执行的,返回执行的结果
  2. 定义一个 symbol 属性,避免重复
  3. context[fnKey] = this this 就是 xxx.call(obj, 'xx') 的 xxx
  4. 执行后 delete context[fnKey]
Function.prototype.customCall = function(context, ...args){
    if(context === null) context = globalThis
    if(typeof context !== 'object') context = new Object(context)
   
    const fnKey = Symbol()
    context[fnKey] = this
    const res = context[fnKey](...args)
    delete context[fnKey]
    return res
}
apply
  1. customCall调用执行的,返回执行的结果
  2. 定义一个 symbol 属性,避免重复
  3. context[fnKey] = this this 就是 xxx.call(obj, 'xx') 的 xxx .、执行后 delete context[fnKey]
  4. 和自定义 call 不同的是 args 是一个数组
Function.prototype.customApply = function(context, args){
    if(context === null) context = globalThis
    if(typeof context !== 'object') context = new Object(context)
   
    const fnKey = Symbol()
    context[fnKey] = this
    const res = context[fnKey](...args)
    delete context[fnKey]
    return res
}