javascript中this问题

一、this的使用情况

1.在html的事件属性中使用this

  例如:<input type="button" id="button2" value="button222" onclick="javascript:alert(this.id);" />

2.在事件处理函数中使用this

例如:button2.onclick = function(){
alert(this.name);
}

3.如果在全局函数中使用,则this为window对象

例如:alert(this == window);  //true

4.在构造函数中使用this

例如: function  People(name,age){

            this.name = name;

            this.age =  age;

         }

5.在原型模式中使用this

 例如:

function  People(name,age){

            this.name = name;

            this.age =  age;

         }

  Peopel.prototype.getName = function(){

       return this.name;

  }

6.css表达式中使用this

<table width="100" height="100">
      
<tr>
          
<td>
              
<div style="width: expression(this.parentElement.width); 
                    height: expression(this.parentElement.height);"
>
                  division element
</div>
          
</td>
      
</tr>
  
</table>


 

二、this心得 

    其实那个对象调用this所在的对象,那么this就指向当前的对象(注意此时this不位于嵌套闭包函数中);如果直接执行this所在的函数,那么this指向window对象。

    特殊案例:    

function a() {
    alert(this);
}
a.call(null);
关于 a.call(null);  根据ECMAScript262规范规定:如果第一个参数传入的对象调用者是null或者undefined的话,call方法将把全局对象(也就是window)作为this的值。所以,不管你什么时候传入null,其this都是全局对象window。

  

posted @ 2012-12-06 16:10  沙漠孤鹰1140  阅读(151)  评论(0编辑  收藏  举报