談談Javascript的this指標

來源:互聯網
上載者:User
  • JavaScript中的this總是讓人迷惑,應該是js眾所周知的坑之一。個人也覺得js中的this不是一個好的設計,由於this晚綁定的特性,它可以是全域對象,當前對象,或者…有人甚至因為坑大而不用this。
  • JavaScript中的this總是讓人迷惑,應該是js眾所周知的坑之一。個人也覺得js中的this不是一個好的設計,由於this晚綁定的特性,它可以是全域對象,當前對象,或者…有人甚至因為坑大而不用this。
  • 其實如果完全掌握了this的工作原理,自然就不會走進這些坑。來看下以下這些情況中的this分別會指向什麼:
1.全域代碼中的this
  1. alert(this)//window 

全域範圍內的this將會指向全域對象,在瀏覽器中即使window。

2.作為單純的函數調用
function fooCoder(x) {      this.x = x;  }  fooCoder(2);  alert(x);// 全域變數x值為2 

這裡this指向了全域對象,即window。在strict 模式中,則是undefined。

3.作為對象的方法調用
var name = "clever coder";  var person = {      name : "foocoder",      hello : function(sth){          console.log(this.name + " says " + sth);      }  }  person.hello("hello world"); 

輸出 foocoder says hello world。this指向person對象,即當前對象。

4.作為建構函式
  1. new FooCoder();  

函數內部的this指向新建立的對象。

5.內建函式
var name = "clever coder";  var person = {      name : "foocoder",      hello : function(sth){          var sayhello = function(sth) {              console.log(this.name + " says " + sth);          };          sayhello(sth);      }  }  person.hello("hello world");//clever coder says hello world  

在內建函式中,this沒有按預想的綁定到外層函數對象上,而是綁定到了全域對象。這裡普遍被認為是JavaScript語言的設計錯誤,因為沒有人想讓內建函式中的this指向全域對象。一般的處理方式是將this作為變數儲存下來,一般約定為that或者self:

  1. var name = "clever coder";  var person = {      name : "foocoder",      hello : function(sth){          var that = this;          var sayhello = function(sth) {              console.log(that.name + " says " + sth);          };          sayhello(sth);      }  }  person.hello("hello world");//foocoder says hello world 


6.使用call和apply設定this
  1. person.hello.call(person, "world")

apply和call類似,只是後面的參數是通過一個數組傳入,而不是分開傳入。兩者的方法定義:

  1. call( thisArg [,arg1,arg2,… ] );  // 參數列表,arg1,arg2,...  apply(thisArg [,argArray] );     // 參數數組,argArray 

兩者都是將某個函數綁定到某個具體對象上使用,自然此時的this會被顯式的設定為第一個參數。

簡單地總結

簡單地總結以上幾點,可以發現,其實只有第六點是讓人疑惑的。

其實就可以總結為以下幾點:

1.當函數作為對象的方法調用時,this指向該對象。

2.當函數作為淡出函數調用時,this指向全域對象(strict 模式時,為undefined)

3.建構函式中的this指向新建立的對象

4.嵌套函數中的this不會繼承上層函數的this,如果需要,可以用一個變數儲存上層函數的this。

再總結的簡單點,如果在函數中使用了this,只有在該函數直接被某對象調用時,該this才指向該對象。

  1. obj.foocoder();  
  2. foocoder.call(obj, ...);  
  3. foocoder.apply(obj, …);  
更進一步

我們可能經常會寫這樣的代碼:

  1. $("#some-ele").click = obj.handler;  

如果在handler中用了this,this會綁定在obj上嗎?顯然不是,賦值以後,函數是在回調中執行的,this會綁定到$(“#some-div”)元素上。這就需要理解函數的執行環境。本文不打算長篇贅述函數的執行環境,可以參考《javascript進階程式設計》中對執行環境和範圍鏈的相關介紹。這裡要指出的時,理解js函數的執行環境,會更好地理解this。

那我們如何能解決回呼函數綁定的問題?ES5中引入了一個新的方法,bind():

fun.bind(thisArg[, arg1[, arg2[, ...]]])   thisArg  當綁定函數被調用時,該參數會作為原函數運行時的this指向.當使用new 操作符調用綁定函數時,該參數無效.  arg1, arg2, ...  當綁定函數被調用時,這些參數加上綁定函數本身的參數會按照順序作為原函數運行時的參數. 
  • 該方法建立一個新函數,稱為綁定函數,綁定函數會以建立它時傳入bind方法的第一個參數作為this,傳入bind方法的第二個以及以後的參數加上綁定函數運行時本身的參數按照順序作為原函數的參數來調用原函數.

顯然bind方法可以很好地解決上述問題。

  1. $("#some-ele").click(person.hello.bind(person));  //相應元素被點擊時,輸出foocoder says hello world  

其實該方法也很容易類比,我們看下Prototype.js中bind方法的源碼:

  1. Function.prototype.bind = function(){    var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift();    return function(){      return fn.apply(object,        args.concat(Array.prototype.slice.call(arguments)));    };  };  
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.