首頁  >  文章  >  web前端  >  理解javascript中的Function.prototype.bind的方法

理解javascript中的Function.prototype.bind的方法

高洛峰
高洛峰原創
2017-02-03 13:35:29974瀏覽

在初學Javascript時,我們也許不需要擔心函數綁定的問題,但是當我們需要在另一個函數中保持上下文對象this時,就會遇到相應的問題了,我見過很多人處理這種問題都是先將this賦值給一個變數(例如self、_this、that等),尤其是var that = this是我見的最多的,這樣當你改變環境之後就可以使用它。這些都是可以的,但是還有一種更好的、更專有的方法,那就是使用Function.prototype.bind,下面進行詳盡的講解。

第一部分:需要解決的問題

首先看下面的程式碼

var myObj = {
 
  specialFunction: function () {
 
  },
 
  anotherSpecialFunction: function () {
 
  },
 
  getAsyncData: function (cb) {
    cb();
  },
 
  render: function () {
this.getAsyncData(function () {
      this.specialFunction();
      this.anotherSpecialFunction();
    });
  }
};
 
myObj.render();

   

這裡我希望創建一個對象,包含了前面兩個普通的方法;第三個方法可以傳遞一個函數,傳入一個函數,傳入一個函數,傳入一個函數,傳入一個函數,傳入一個函數,傳入一個函數,傳入一個函數,傳入一個函數,傳入一個函數,傳入一個函數,傳入兩個普通方法;的這個函數立即執行;最後一個方法會呼叫myObj物件的getAsyncData方法,這裡使用了this,然後在getAsyncData方法中傳入了一個函數,這個函數繼續呼叫這個物件的前兩個方法,仍使用了this,這時很多人其實可以看出問題所在了,將上述程式碼輸入控制台,得到下面的結果:

TypeError: this.specialFunction is not a function

第二部分:問題剖析

在物件中render方法中的this的確是指向myObj物件的,所以我們可以透過this.getAsyncData來呼叫這個物件中的函數,但是當我們給其傳遞函數作為參數時,這裡的this就指向了全域環境window了,因為全域環境中沒有物件中的前兩個方法,所以才會報錯。

第三部分:解決問題的幾種方式

所以我們需要做的就是正確調用對像中的前兩個方法,很多人使用的方法便是首先在對象的環境中獲取this賦值給另一個變量,這時就可以在後面的環境中呼叫了,如下所示:

render: function () {
  var that = this;
  this.getAsyncData(function () {
    that.specialFunction();
    that.anotherSpecialFunction();
  });
}

雖然這種方法是可行的,但是使用Function.prototype.bind()會使程式碼更清晰、易懂,如下所說明:

render: function () {
 
  this.getAsyncData(function () {
 
    this.specialFunction();
 
    this.anotherSpecialFunction();
 
  }.bind(this));
 
}

   

這裡我們成功地把this綁定到了環境中。

下面是另一個簡單的例子:

var foo = {
  x: 3
}
 
var bar = function(){
  console.log(this.x);
}
 
bar(); // undefined
 
var boundFunc = bar.bind(foo);
 
boundFunc(); // 3

   

下面的例子也是常見的:

this.x = 9;  // this refers to global "window" object here in the browser
var module = {
 x: 81,
 getX: function() { return this.x; }
};
 
module.getX(); // 81
 
var retrieveX = module.getX;
retrieveX(); 
// returns 9 - The function gets invoked at the global scope
 
// Create a new function with 'this' bound to module
// New programmers might confuse the
// global var x with module's property x
var boundGetX = retrieveX.bind(module);
boundGetX(); // 81

   

支援的,所以我們可以使用MDN提供的方法來讓IE低版支援.bind()方法:

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,
                aArgs.concat(Array.prototype.slice.call(arguments)));
    };
 
  fNOP.prototype = this.prototype;
  fBound.prototype = new fNOP();
 
  return fBound;
 };
}

   

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支PHP中文網。

更多理解javascript中的Function.prototype.bind的方法相關文章請關注PHP中文網!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn