javascript中this是什麼

來源:互聯網
上載者:User

this在javascript中 情況是不同與java  c++, 

誰調用了  this對象所在的函數,  this就指向誰

this引用的對象被 稱為函數的 上下文  ,它不是由如何聲明函數,而是由如何調用函數決定的.

根據函數如何被調用,同一個函數可以擁有不同的上下文

<script type="text/javascript">      
//this是什麼   
var o1={handle:'o1'};                                  
var o2={handle:'o2'};                                  
var o3={handle:'o3'};              
window.handle='window';   
  
function whoAmI(){   
    return this.handle;            
}      
       
o1.identifyMe =whoAmI;         
  
alert(whoAmI());  //結果  window   
alert(o1.identifyMe()); //結果o1   
alert(whoAmI.call(o2)); //結果o2   
alert(whoAmI.apply(o3)); //結果o3   
</script>   

--------------------------------------------------------------------------

頂層函數是window對象的屬性(方法) , 下面的test8(),就是頂層函數

<script type="text/javascript">    
    function test8()   
    {   
        alert(this==window)                    
    }   
    test8();   
  
  
  
</script>  

 

上面代碼執行結果為 true,  test8函數被包含在一個名為window的全域對象中,test8函數是window對象的一個方法.所以this 指向window全域對象

----------------------------------------------------

 

<script type="text/javascript">    
    function test8()   
    {   
        alert(this==window)                    
    }   
   
</script>   
  
<input type="button" value="test 8"  id="bu4" onclick="test8()" /><br/>  

上面代碼執行結果為 true  ,this是window對象

---------------------------------------------------

 

<script type="text/javascript">      
    function test8()   
    {   
        alert(arguments[0].id)                     
    }              
</script>   
<input type="button" value="test 8"  id="bu4" onclick="test8(this)" class="cla"/>  

上面代碼執行結果為bu4, 這裡的this是  button對象
-------------------------------------------------------

 

<input type="button" value="test" id="bu5"/><br/>   
<script type="text/javascript">      
    function test11()   
    {   
        var obj=document.getElementById('bu5');   
        obj.onclick=function(){   
            alert(this.id)   
        }                  
    }   
    test11()               
</script>  

上面代碼執行結果為bu5 , 這裡的this是  button對象 ,因為obj.onclick=function(){}  ,是為button註冊了個匿名函數 ,這個匿名函數 是obj對象(button)的 函數.

------------------------------------------------------- 

 

聯繫我們

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