淺析Javascript中bind()方法的使用與實現_javascript技巧

來源:互聯網
上載者:User

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

var altwrite = document.write; 
altwrite("hello"); 
//1.以上代碼有什麼問題
//2.正確操作是怎樣的
//3.bind()方法怎麼實現

對於上面這道題目,答案並不是太難,主要考點就是this指向的問題,altwrite()函數改變this的指向global或window對象,導致執行時提示非法調用異常,正確的方案就是使用bind()方法:

altwrite.bind(document)("hello") 
當然也可以使用call()方法:

altwrite.call(document, "hello") 
本文的重點在於討論第三個問題bind()方法的實現,在開始討論bind()的實現之前,我們先來看看bind()方法的使用:

綁定函數
bind()最簡單的用法是建立一個函數,使這個函數不論怎麼調用都有同樣的this值。常見的錯誤就像上面的例子一樣,將方法從對象中拿出來,然後調用,並且希望this指向原來的對象。如果不做特殊處理,一般會丟失原來的對象。使用bind()方法能夠很漂亮的解決這個問題:

this.num = 9; var mymodule = {  num: 81, getNum: function() { return this.num; }};module.getNum(); // 81var getNum = module.getNum; getNum(); // 9, 因為在這個例子中,"this"指向全域對象// 建立一個'this'綁定到module的函數var boundGetNum = getNum.bind(module); boundGetNum(); // 81 

偏函數(Partial Functions)

Partial Functions也叫Partial Applications,這裡截取一段關於偏函數的定義:

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.

這是一個很好的特性,使用bind()我們設定函數的預定義參數,然後調用的時候傳入其他參數即可:

function list() {  return Array.prototype.slice.call(arguments);}var list1 = list(1, 2, 3); // [1, 2, 3]// 預定義參數37var leadingThirtysevenList = list.bind(undefined, 37);var list2 = leadingThirtysevenList(); // [37] var list3 = leadingThirtysevenList(1, 2, 3); // [37, 1, 2, 3] 

和setTimeout一起使用

一般情況下setTimeout()的this指向window或global對象。當使用類的方法時需要this指向類執行個體,就可以使用bind()將this綁定到回呼函數來管理執行個體。

function Bloomer() {  this.petalCount = Math.ceil(Math.random() * 12) + 1;}// 1秒後調用declare函數Bloomer.prototype.bloom = function() {  window.setTimeout(this.declare.bind(this), 1000);};Bloomer.prototype.declare = function() {  console.log('我有 ' + this.petalCount + ' 朵花瓣!');};

注意:對於事件處理函數和setInterval方法也可以使用上面的方法

綁定函數作為建構函式

綁定函數也適用於使用new操作符來構造目標函數的執行個體。當使用綁定函數來構造執行個體,注意:this會被忽略,但是傳入的參數仍然可用。

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*/); // 實現中的例子不支援,// 原生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運算子判斷時為true。

捷徑

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

例如要將一個類數組對象轉換為真正的數組,可能的例子如下:

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

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

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

實現

上面的幾個小節可以看出bind()有很多的使用情境,但是bind()函數是在 ECMA-262 第五版才被加入;它可能無法在所有瀏覽器上運行。這就需要我們自己實現bind()函數了。

首先我們可以通過給目標函數指定範圍來簡單實現bind()方法:

Function.prototype.bind = function(context){  self = this; //儲存this,即調用bind方法的目標函數 return function(){   return self.apply(context,arguments); };};

考慮到函數柯裡化的情況,我們可以構建一個更加健壯的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()方法可以綁定對象,也支援在綁定的時候傳參。

繼續,Javascript的函數還可以作為建構函式,那麼綁定後的函數用這種方式調用時,情況就比較微妙了,需要涉及到原型鏈的傳遞:

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》一書中對bind()的實現:通過設定一個中轉建構函式F,使綁定後的函數與調用bind()的函數處於同一原型鏈上,用new操作符調用綁定後的函數,返回的對象也能正常使用instanceof,因此這是最嚴謹的bind()實現。

對於為了在瀏覽器中能支援bind()函數,只需要對上述函數稍微修改即可:

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()方法的使用與實現就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.