bind() 理解 【转】

bind()可稍后执行  call()  apply()

 

 

为了搞清这个陌生又熟悉的bind,google一下,发现javascript1.8.5版本中原生实现了此方法,目前IE9+,ff4+,chrome7+支持此方法,opera和safari不支持(MDN上的说明)。 
bind的作用和apply,call类似都是改变函数的execute context,也就是 runtime 时 this 关键字的指向。但是使用方法略有不同。一个函数进行bind后可稍后执行。

 bind 方法实现:绑定this  和 “科里化”:

function getConfig(colors,size,otherOptions){

  console.log(colors,size,otherOptions)

}

var defaultConfig = getConfig.bind(null,"#f00","1024*768");

defaultConfig("123");  //#f00 1024*768 123

defaultConfig("345");  //#f00 1024*768 345

因为bind 方法是EMS5 以后提出的方法,对于老的浏览器,可以使用手写一个bind 方法

if(!Function.prototype.bind){

  Function.prototype.bind = function(oThis){

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

      throw new TypeError('What is trying to be bound is not callable')

    }

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

      fToBind = this,

      fNOP = function(){};

      fBound = function(){

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

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

      }

    fNOP.prototype = this.prototype;

    fBound.prototype = new fNOP();

    return fBound;

  }

}

posted @ 2017-04-20 14:23  铁塔  阅读(273)  评论(0编辑  收藏  举报