bind() 函數兼容


為了搞清這個陌生又熟悉的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;

  }

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM