this
在JavaScript中,this通常指向的是我們正在執行的函數本身,或者是指向該函數所屬的對象(運行時)。當我們在頁面中定義了函數 doSomething()的時候,它的owner是頁面,或者是JavaScript中的window對象(或 global對象)。對於一個onclick屬性,它為它所屬的HTML元素所擁有,this應該指向該HTML元素。
2.1在幾種常見情境中this的變化
函數樣本
function doSomething ()
{
alert(this.navigator); //appCodeName
this.value = "I am from the Object constructor";
this.style.backgroundColor = "# 000000";
}
1. (A)作為普通函數直接調用時,this指向window對象.
2. (B)作為控制項事件觸發時
1) inline event registration 內聯事件註冊 .將事件直接寫在HTML代碼中(<element
onclick=”doSomething()”>), 此時this指向 window對象 。
2) Traditional event registration 傳統事件註冊 (DHTML方式).
形如 element.onclick = doSomething; 此時this指向 element對象
3) <element onclick=”doSomething(this)”>作為參數傳遞可以指向element
3. (C)作為對象使用時this指向當前對象。形如:new doSomething();
4. (D)使用apply 或者call方法時,this指向所傳遞的對象。
形如:var obj={}; doSomething.apply(obj,new Array(”nothing”); //thisàobj
追加:如果希望事件調用時仍然把this指定為特定的對象,可以通過以下方法實現:
Function.prototype.bind = function(obj)
{
var method = this;
var temp = function()
{
return method.apply(obj, arguments);
};
return temp;
}
function load()
{
this.aa = "hello";
this.show = function()
{
alert(this.aa);
};
}
var newclass = new load();
document.body.onload = newclass.show.bind(newclass);