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            
}

 

转载于:https://www.cnblogs.com/izyk/p/11434401.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值