call、apply 的模拟实现

1. call的模拟实现

Function.prototype.myCall = function (context = window, ...args) {
  context = context || window  // 如果没有context参数,就返回window
    
  if (this === Function.prototype) {
    return undefined  // 直接调用Function.prorotype.myCall() 反回undefined       
  }

  fn = Symbol()
  context[fn] = this  // 为context设置Symbol属性,并将当前函数赋给该属性
  const result = context[fn](...args)  // 将参数传入 
  delete context[fn]  // 删除该属性 
  return result         
}

Symbol属性特性: 唯一性,可以作为对象的属性,有静态属性Symbol.iterator

 

2. apply的模拟实现

Function.prototype.myApply = function (context = window, args) {
  context = context || window
  
  if (this === Function.prototype) {
    retrun undefined
  }
  
  fn = Symbol()
  context[fn] = this

  let result
  if ( Array.isArray(args) ) {
    result = context[fn](...args)
  }  else {
    result = context[fn]()
  }
  delete context[fn]  
  return result            
}

 

posted @ 2019-08-30 12:47  izyk  阅读(151)  评论(0编辑  收藏  举报