javascript中this是什么

本文深入解析了JavaScript中this关键字的工作原理及其使用场景。通过多个示例展示了this如何根据函数调用方式的不同而改变其指向的对象。

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

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

 

转载于:https://www.cnblogs.com/qiantuwuliang/archive/2009/07/19/1526647.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值