欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

關(guān)于原生js中bind函數(shù)的簡(jiǎn)單實(shí)現(xiàn)

 更新時(shí)間:2016年08月10日 10:28:17   投稿:jingxian  
下面小編就為大家?guī)?lái)一篇關(guān)于原生js中bind函數(shù)的簡(jiǎn)單實(shí)現(xiàn)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

今天繼續(xù)研究了bind函數(shù)的實(shí)現(xiàn),也知道了shim和polyfill的說(shuō)法,現(xiàn)在總結(jié)一下,

if (!Function.prototype.bind) {
 Function.prototype.bind = function (oThis) {
  if (typeof this !== "function") {
   // closest thing possible to the ECMAScript 5 internal IsCallable function
   throw new TypeError("Function.prototype.bind - 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 && oThis
                 ? this
                 : oThis || window,
                aArgs.concat(Array.prototype.slice.call(arguments)));
    };

  fNOP.prototype = this.prototype;
  fBound.prototype = new fNOP();

  return fBound;
 };
}

這是官方文檔上的實(shí)現(xiàn),我分二個(gè)方面來(lái)談我要說(shuō)的東西,

第一個(gè)是參數(shù),agruments的使用

var aArgs = Array.prototype.slice.call(arguments, 1),這里是將bind函數(shù)的參數(shù)數(shù)組取出來(lái),第一個(gè)參數(shù)不要(就是不要oThis)也就是要被綁定方法的那個(gè)對(duì)象,第二個(gè)是

aArgs.concat(Array.prototype.slice.call(arguments))); 這里是用了數(shù)組的方法,把參數(shù)插在參數(shù)數(shù)組后面,要注意,這個(gè)函數(shù)是要被return 出去然后執(zhí)行的,他的參數(shù)數(shù)組是return出去的那個(gè)fBound函數(shù)的參數(shù)數(shù)組,所以上下兩個(gè)參數(shù)數(shù)組是不一樣的,有點(diǎn)像柯里化。

第二個(gè)是上下文,在其中上下文的變化比較難理解,bind函數(shù)主要就是為了綁定上下文來(lái)使用的

fToBind = this 這里是保存了對(duì)象的上下文,緊接著下面的apply方法讓要被綁定的那個(gè)對(duì)象可以使用該上下文

fNOP.prototype = this.prototype;

fBound.prototype = new fNOP();

這里是以fNOP為中介把this.prototype這個(gè)原對(duì)象的屬性給fBound,確保fBound是在定義的時(shí)候的那個(gè)上下文里面執(zhí)行。本來(lái)

bound.prototype = self.prototype就可以將原屬性集成過(guò)來(lái)了,但是這樣兩個(gè)對(duì)象屬性都指向同一個(gè)地方,修改 bound.prototype 將會(huì)造成self.prototype 也發(fā)生改變,這樣并不是我們的本意。所以通過(guò)一個(gè)空函數(shù) nop 做中轉(zhuǎn),能有效的防止這種情況的發(fā)生。

以上這篇關(guān)于原生js中bind函數(shù)的簡(jiǎn)單實(shí)現(xiàn)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論