this在javascript中 情况是不同与java c++,
谁调用了 this对象所在的函数, this就指向谁
this引用的对象被 称为函数的 上下文 ,它不是由如何声明函数,而是由如何调用函数决定的.
根据函数如何被调用,同一个函数可以拥有不同的上下文
// 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(),就是顶层函数
function test8()
{
alert( this == window)
}
test8();
< / script>
上面代码执行结果为 true, test8函数被包含在一个名为window的全局对象中,test8函数是window对象的一个方法.所以this 指向window全局对象
----------------------------------------------------
function test8()
{
alert( this == window)
}
< / script>
< input type = " button " value = " test 8 " id = " bu4 " onclick = " test8() " / ><br / >
上面代码执行结果为 true ,this是window对象
---------------------------------------------------
function test8()
{
alert(arguments[ 0 ].id)
}
< / script>
< input type = " button " value = " test 8 " id = " bu4 " onclick = " test8(this) " class = " cla "/ >
上面代码执行结果为bu4, 这里的this是 button对象
-------------------------------------------------------
< 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)的 函数.
-------------------------------------------------------