js 中的this

來源:互聯網
上載者:User

標籤:

this是js的一個關鍵字,隨著函數使用場合不同,this的值會發生變化。但是總有一個原則,那就是this指的是調用函數的那個對象。

 1、純粹函數調用。

 
  1. function test() {     
  2.     this.x = 1;      
  3.     alert(x);  
  4. }  
  5.   
  6. test(); 

 


其實這裡的this就是全域變數。看下面的例子就能很好的理解其實this就是全域對象Global。其實這裡的this就是全域變數。看下面的例子就能很好的理解其實this就是全域對象Global。

 

 
  1. var x = 1;  
  2. function test() {  
  3.     alert(this.x);  
  4. }  
  5. test();//1  
  6.   
  7. var x = 1;  
  8. function test() {  
  9.     this.x = 0;  
  10. }  
  11. test();  
  12. alert(x);//0  

 2、作為對象方法調用,那麼this就是指這個上級對象。

 
  1. function test() {  
  2.     alert(this.x);  
  3. }  
  4.   
  5. var o = {};  
  6. o.x = 1;  
  7. o.m = test;  
  8. o.m(); //1  


3、作為建構函式調用。所謂建構函式,就是產生一個新的對象。這時,這個this就是指這個對象。

 
  1. function test() {      
  2.      this.x = 1;  
  3. }  
  4. var o = new test();  
  5. alert(o.x);//1  


4、apply調用

 
  1. var x = 0;  
  2. function test() {  
  3.     alert(this.x);  
  4. }  
  5.   
  6. var o = {};  
  7. o.x = 1;  
  8. o.m = test;  
  9. o.m.apply(); //0  
  10. o.m.apply(o);//1  


當apply沒有參數時,表示為全域對象。所以值為0。

 

文章來源:http://blog.csdn.net/zhikun518/article/details/7936603

js 中的this

聯繫我們

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