this,你是誰?

在js中this不像其它語言那樣容易理解,它有時候指window對象,有時候又是其它對象,那麼this,你究竟是誰呢?
要分析this就要先理解js中的方法定義,由於this通常都是在方法中使用的,並且方法在js中的地位又很特殊。 函數


在js中定義的方法必定不會單獨存在,它一定屬於某個對象,因此this就是表明方法屬於的那個對象。this

一、通常方法spa

 

function test() { 
    alert(this==window); 
} 
test();

像這種普通的方法定義,方法並無屬於某個對象呀?其實js裏有個全局的window對象,沒錯,這個方法就是定義在window對象下了,因此裏面的this確定就是window。prototype

二、方法,仍是方法code

function test1(){

    function test2(){ 
        alert(this==window) 
    } 
    test2() 
} 
test1();

這種狀況呢,test2沒有明顯的屬於某個對象,那它就...對,那它就屬於window對象,因此裏面的this就是指window對象。對象

三、對象的方法blog

var o={ 
    test:function(){ 
        alert(this==window); 
    }    
} 
o.test(); 

這種狀況就很容易理解了,test方法屬於o對象,this固然是指o對象了。事件

四、再見對象get

function Persion () { 
    this.name="mu"; 
}

Persion.prototype.show=function(){ 
    alert(this.name); 
}

var p=new Persion();

p.show();

再來看Persion方法,這裏的Persion是構造函數,因此this就是指new的時候js建立的匿名對象,這個匿名對象又賦給了p對象,因而this就是指p對象。io

五、別忘了事件

var btn=document.getElementById("btn"); 
btn.onclick=function(){ 
    alert(this); 
} 

onclick方法屬於btn對象,因此this指向btn

btn.addEventListener("click",function(){ 
    alert(this); 
})

btn.attachEvent("onclick",function(){ 
    alert(this); 
});

這裏比較特殊了,前者是W3C標準的,this指向btn,後者是ie專有的,this指定window,這裏只能死記了。


 

最後總結一句話:this表明誰,就看方法屬於誰,ie事件綁定指window對象!

相關文章
相關標籤/搜索