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)的 函數.
-------------------------------------------------------