淺析Javascript中bind()方法的使用與實(shí)現(xiàn)
來(lái)源:易賢網(wǎng) 閱讀:700 次 日期:2016-07-06 11:37:41
溫馨提示:易賢網(wǎng)小編為您整理了“淺析Javascript中bind()方法的使用與實(shí)現(xiàn)”,方便廣大網(wǎng)友查閱!

下面小編就為大家?guī)?lái)一篇淺析Javascript中bind()方法的使用與實(shí)現(xiàn)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,一起跟隨小編過(guò)來(lái)看看吧

在討論bind()方法之前我們先來(lái)看一道題目:

var altwrite = document.write;  

altwrite("hello");  

//1.以上代碼有什么問(wèn)題

//2.正確操作是怎樣的

//3.bind()方法怎么實(shí)現(xiàn)

對(duì)于上面這道題目,答案并不是太難,主要考點(diǎn)就是this指向的問(wèn)題,altwrite()函數(shù)改變this的指向global或window對(duì)象,導(dǎo)致執(zhí)行時(shí)提示非法調(diào)用異常,正確的方案就是使用bind()方法:

altwrite.bind(document)("hello")  

當(dāng)然也可以使用call()方法:

altwrite.call(document, "hello")  

本文的重點(diǎn)在于討論第三個(gè)問(wèn)題bind()方法的實(shí)現(xiàn),在開(kāi)始討論bind()的實(shí)現(xiàn)之前,我們先來(lái)看看bind()方法的使用:

綁定函數(shù)

bind()最簡(jiǎn)單的用法是創(chuàng)建一個(gè)函數(shù),使這個(gè)函數(shù)不論怎么調(diào)用都有同樣的this值。常見(jiàn)的錯(cuò)誤就像上面的例子一樣,將方法從對(duì)象中拿出來(lái),然后調(diào)用,并且希望this指向原來(lái)的對(duì)象。如果不做特殊處理,一般會(huì)丟失原來(lái)的對(duì)象。使用bind()方法能夠很漂亮的解決這個(gè)問(wèn)題:

this.num = 9; 

var mymodule = { 

 num: 81,

 getNum: function() { return this.num; }

};

module.getNum(); // 81

var getNum = module.getNum; 

getNum(); // 9, 因?yàn)樵谶@個(gè)例子中,"this"指向全局對(duì)象

// 創(chuàng)建一個(gè)'this'綁定到module的函數(shù)

var boundGetNum = getNum.bind(module); 

boundGetNum(); // 81 

偏函數(shù)(Partial Functions)

Partial Functions也叫Partial Applications,這里截取一段關(guān)于偏函數(shù)的定義:

Partial application can be described as taking a function that accepts some number of arguments, binding values to one or more of those arguments, and returning a new function that only accepts the remaining, un-bound arguments.

這是一個(gè)很好的特性,使用bind()我們?cè)O(shè)定函數(shù)的預(yù)定義參數(shù),然后調(diào)用的時(shí)候傳入其他參數(shù)即可:

function list() { 

 return Array.prototype.slice.call(arguments);

}

var list1 = list(1, 2, 3); // [1, 2, 3]

// 預(yù)定義參數(shù)37

var leadingThirtysevenList = list.bind(undefined, 37);

var list2 = leadingThirtysevenList(); // [37] 

var list3 = leadingThirtysevenList(1, 2, 3); // [37, 1, 2, 3] 

和setTimeout一起使用

一般情況下setTimeout()的this指向window或global對(duì)象。當(dāng)使用類的方法時(shí)需要this指向類實(shí)例,就可以使用bind()將this綁定到回調(diào)函數(shù)來(lái)管理實(shí)例。

function Bloomer() { 

 this.petalCount = Math.ceil(Math.random() * 12) + 1;

}

// 1秒后調(diào)用declare函數(shù)

Bloomer.prototype.bloom = function() { 

 window.setTimeout(this.declare.bind(this), 1000);

};

Bloomer.prototype.declare = function() { 

 console.log('我有 ' + this.petalCount + ' 朵花瓣!');

};

注意:對(duì)于事件處理函數(shù)和setInterval方法也可以使用上面的方法

綁定函數(shù)作為構(gòu)造函數(shù)

綁定函數(shù)也適用于使用new操作符來(lái)構(gòu)造目標(biāo)函數(shù)的實(shí)例。當(dāng)使用綁定函數(shù)來(lái)構(gòu)造實(shí)例,注意:this會(huì)被忽略,但是傳入的參數(shù)仍然可用。

function Point(x, y) { 

 this.x = x;

 this.y = y;

}

Point.prototype.toString = function() { 

 return this.x + ',' + this.y; 

};

var p = new Point(1, 2); 

p.toString(); // '1,2'

var emptyObj = {}; 

var YAxisPoint = Point.bind(emptyObj, 0/*x*/); 

// 實(shí)現(xiàn)中的例子不支持,

// 原生bind支持:

var YAxisPoint = Point.bind(null, 0/*x*/);

var axisPoint = new YAxisPoint(5); 

axisPoint.toString(); // '0,5'

axisPoint instanceof Point; // true 

axisPoint instanceof YAxisPoint; // true 

new Point(17, 42) instanceof YAxisPoint; // true 

上面例子中Point和YAxisPoint共享原型,因此使用instanceof運(yùn)算符判斷時(shí)為true。

捷徑

bind()也可以為需要特定this值的函數(shù)創(chuàng)造捷徑。

例如要將一個(gè)類數(shù)組對(duì)象轉(zhuǎn)換為真正的數(shù)組,可能的例子如下:

var slice = Array.prototype.slice;

// ...

slice.call(arguments);

如果使用bind()的話,情況變得更簡(jiǎn)單:

var unboundSlice = Array.prototype.slice; 

var slice = Function.prototype.call.bind(unboundSlice);

// ...

slice(arguments); 

實(shí)現(xiàn)

上面的幾個(gè)小節(jié)可以看出bind()有很多的使用場(chǎng)景,但是bind()函數(shù)是在 ECMA-262 第五版才被加入;它可能無(wú)法在所有瀏覽器上運(yùn)行。這就需要我們自己實(shí)現(xiàn)bind()函數(shù)了。

首先我們可以通過(guò)給目標(biāo)函數(shù)指定作用域來(lái)簡(jiǎn)單實(shí)現(xiàn)bind()方法:

Function.prototype.bind = function(context){ 

 self = this; //保存this,即調(diào)用bind方法的目標(biāo)函數(shù)

 return function(){

   return self.apply(context,arguments);

 };

};

考慮到函數(shù)柯里化的情況,我們可以構(gòu)建一個(gè)更加健壯的bind():

Function.prototype.bind = function(context){ 

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

 self = this;

 return function(){

   var innerArgs = Array.prototype.slice.call(arguments);

   var finalArgs = args.concat(innerArgs);

   return self.apply(context,finalArgs);

 };

};

這次的bind()方法可以綁定對(duì)象,也支持在綁定的時(shí)候傳參。

繼續(xù),Javascript的函數(shù)還可以作為構(gòu)造函數(shù),那么綁定后的函數(shù)用這種方式調(diào)用時(shí),情況就比較微妙了,需要涉及到原型鏈的傳遞:

Function.prototype.bind = function(context){ 

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

 F = function(){},

 self = this,

 bound = function(){

   var innerArgs = Array.prototype.slice.call(arguments);

   var finalArgs = args.concat(innerArgs);

   return self.apply((this instanceof F ? this : context), finalArgs);

 };

 F.prototype = self.prototype;

 bound.prototype = new F();

 return bound;

};

這是《JavaScript Web Application》一書中對(duì)bind()的實(shí)現(xiàn):通過(guò)設(shè)置一個(gè)中轉(zhuǎn)構(gòu)造函數(shù)F,使綁定后的函數(shù)與調(diào)用bind()的函數(shù)處于同一原型鏈上,用new操作符調(diào)用綁定后的函數(shù),返回的對(duì)象也能正常使用instanceof,因此這是最嚴(yán)謹(jǐn)?shù)腷ind()實(shí)現(xiàn)。

對(duì)于為了在瀏覽器中能支持bind()函數(shù),只需要對(duì)上述函數(shù)稍微修改即可:

Function.prototype.bind = function (oThis) { 

  if (typeof this !== "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;

 };

以上這篇淺析Javascript中bind()方法的使用與實(shí)現(xiàn)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考

更多信息請(qǐng)查看網(wǎng)絡(luò)編程
易賢網(wǎng)手機(jī)網(wǎng)站地址:淺析Javascript中bind()方法的使用與實(shí)現(xiàn)
由于各方面情況的不斷調(diào)整與變化,易賢網(wǎng)提供的所有考試信息和咨詢回復(fù)僅供參考,敬請(qǐng)考生以權(quán)威部門公布的正式信息和咨詢?yōu)闇?zhǔn)!

2025國(guó)考·省考課程試聽(tīng)報(bào)名

  • 報(bào)班類型
  • 姓名
  • 手機(jī)號(hào)
  • 驗(yàn)證碼
關(guān)于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡(jiǎn)要咨詢 | 簡(jiǎn)要咨詢須知 | 新媒體/短視頻平臺(tái) | 手機(jī)站點(diǎn) | 投訴建議
工業(yè)和信息化部備案號(hào):滇ICP備2023014141號(hào)-1 云南省教育廳備案號(hào):云教ICP備0901021 滇公網(wǎng)安備53010202001879號(hào) 人力資源服務(wù)許可證:(云)人服證字(2023)第0102001523號(hào)
云南網(wǎng)警備案專用圖標(biāo)
聯(lián)系電話:0871-65099533/13759567129 獲取招聘考試信息及咨詢關(guān)注公眾號(hào):hfpxwx
咨詢QQ:1093837350(9:00—18:00)版權(quán)所有:易賢網(wǎng)
云南網(wǎng)警報(bào)警專用圖標(biāo)