1、this總是指向函數的直接調用者(而非間接調用者);
2、如果有new關鍵字,this指向new出來的那個對象;
3、在事件中,this指向觸發這個事件的對象,特殊的是,IE中的attachEvent中的this總是指向全局對象
Window;
看看下邊幾個例子,或許可以更好的理解this對象
this的指向
this表示當前對象,this的指向是根據調用的上下文來決定的,默認指向window對象
全局環境
全局環境就是在<script></script>里面,這里的this始終指向的是window對象,
<script>console.log(this)</script> 指向window對象
局部環境
在全局作用域下直接調用函數,this指向window
<script>
function func(){
console.log(this) ;//this指向的還是window對象
}
func();
</script>
對象函數調用,哪個對象調用就指向哪個對象
<input type="button"id="btnOK" value="OK">
<script>
varbtnOK=document.getElementById("btnOK");
btnOK.onclick=function(){
console.log(this);//this指向的是btnOK對象
}
</script>
使用 new 實例化對象,在構造函數中的this指向實例化對象。
<script>
var Show=function(){
this.myName="Mr.Cao"; //這里的this指向的是obj對象
}
var obj=new Show();
</script>
使用call或apply改變this的指向
<script>
var Go=function(){
this.address="深圳";
}
var Show=function(){
console.log(this.address);//輸出 深圳
}
var go=new Go();
Show.call(go);//改變Show方法的this指向go對象
</script>