一、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。