其他分享
首页 > 其他分享> > 用es3的语法实现bind

用es3的语法实现bind

作者:互联网

如何用es3的语法实现bind?

function bind(fn, self) {
  if (typeof self === 'object' && self !== null || typeof self === 'function') {
    const random = Math.random()
    //存储函数 this指向为self
    self[random] = fn
    //获取参数的字符形式
    var args = [].slice.call(arguments, 2)   
    if (args.length) {
      args += ','
    }
    return function () {    
      argsTwo = arguments.length? [].slice.call(arguments) : ''
      //参数拼接起来
      var endArgs = args.toString() + argsTwo.toString()
      //获取返回值
      var result = eval('self[random]'+'('+endArgs+')')
      //删除生成的属性
      delete self[random]
      return result
    } 
  }else {
    throw new TypeError('[err :] this is primitive')
  }  
}

  

标签:function,args,es3,bind,self,random,语法,arguments,var
来源: https://www.cnblogs.com/xiaomactx/p/14493284.html