手写bind

1.普通版

if(Function.prototype.bind === undefined){

  console.log('您的浏览器不支持bind方法,使用手写bind功能')

  Function.prototype.bind = function(obj){

    var arg1 = [].slice.call(arguments,1)

    var fun = this

    return function(){

    fun.apply(obj,arg1.concat([].slice.call(arguments,1)))

    }

  }

}else{

  console.log('您的浏览器支持bind方法')

}

2. MDN标准源码

if(!Function.prototype.bind) {

  Function.prototype.bind = function(oThis) {

    if(typeof this !== 'function') {

      throw new TypeError('Error')

    }

  var args = Array.prototype.slice.call(arguments,1)

  var fToBind = this

  var fNOP = function(){}

  var fBound = function() {

    return fToBind.apply(this instanceof fNOP && oThis ? this : oThis || window,

              args.concat(Array.prototype.slice.call(arguments)))

  }

  fNOP.prototype = this.prototype

  fBound.prototype = new fNOP()

  return fBound

  }

}

————学习记录

posted @ 2020-07-17 14:30  桃李子  阅读(92)  评论(0)    收藏  举报