① this指向的,永遠只多是對象!
② this指向誰,永遠不取決於this寫在哪!而是取決於函數在哪調用。
③ this指向的對象,咱們稱之爲函數的上下文context,也叫函數的調用者。數組
下面,請看具體狀況。bash
① 經過函數名()直接調用:this指向window函數
function func(){
console.log(this);
}
//① 經過函數名()直接調用:this指向window
func(); // this--->window複製代碼
② 經過對象.函數名()調用的:this指向這個對象
ui
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指向這個數組
this
function func(){
console.log(this);
}
//③ 函數做爲數組的一個元素,經過數組下標調用的:this指向這個數組
var arr = [func,1,2,3];
arr[0](); // this--->arr複製代碼
④ 函數做爲window內置函數的回調函數調用:this指向window( setInterval setTimeout 等)
spa
function func(){
console.log(this);
}
//④ 函數做爲window內置函數的回調函數調用:this指向window
setTimeout(func,1000);// this--->window
//setInterval(func,1000);複製代碼
⑤ 函數做爲構造函數,用new關鍵字調用時:this指向新new出的對象
code
function func(){
console.log(this);
}
//⑤ 函數做爲構造函數,用new關鍵字調用時:this指向新new出的對象
var obj = new func(); //this--->new出的新obj複製代碼