關於this的指向,是一個令人很頭疼的問題。但是,你運氣好,碰到了我。老夫這兒有本祖傳秘籍,看懂這個,媽媽再也不用擔心你的this指向不對啦!
歸根結底,this指向就一句話:誰最終調用函數,this指向誰!!!
關於這點,老夫有三言相贈:
① this指向的,永遠只可能是對象!
② this指向誰,永遠不取決於this寫在哪!而是取決於函數在哪調用。
③ this指向的對象,我們稱之為函數的上下文context,也叫函數的調用者。
下面,請看具體情況。
① 通過函數名()直接調用:this指向window
function func(){
console.log(this);
}
//① 通過函數名()直接調用:this指向window
func(); // this--->window
② 通過對象.函數名()調用的:this指向這個對象
function func(){
console.log(this);
}
//② 通過對象.函數名()調用的:this指向這個對象
// 狹義對象
var obj = {
name:"obj",
func1 :func
};
obj.func1(); // this--->obj
// 廣義對象
document.getElementById("div").onclick = function(){
this.style.backgroundColor = "red";
}; // this--->div
③ 函數作為數組的一個元素,通過數組下標調用的:this指向這個數組
function func(){
console.log(this);
}
//③ 函數作為數組的一個元素,通過數組下標調用的:this指向這個數組
var arr = [func,1,2,3];
arr[0](); // this--->arr
④ 函數作為window內置函數的回調函數調用:this指向window( setInterval setTimeout 等)
function func(){
console.log(this);
}
//④ 函數作為window內置函數的回調函數調用:this指向window
setTimeout(func,1000);// this--->window
//setInterval(func,1000);
⑤ 函數作為構造函數,用new關鍵字調用時:this指向新new出的對象
function func(){
console.log(this);
}
//⑤ 函數作為構造函數,用new關鍵字調用時:this指向新new出的對象
var obj = new func(); //this--->new出的新obj

