js中this指向的三種情況


js中this指向的幾種情況
一、全局作用域或者普通函數自執行中this指向全局對象window,普通函數的自執行會進行預編譯,然后預編譯this的指向是window

//全局作用域
console.log(this);//Window
//普通函數
function fn(){
console.log(this); //Window
}
fn(); //函數加括號調用叫函數自執行,函數自執行時,內部的this指向頂層對象/window


二、事件函數內部的this指向事件源:注意在事件函數中如果包含普通函數,普通函數自執行后,內部this還是指向window

//事件函數內部的this指向事件源
document.body.onclick = function(){
this.style.height = "1000px";
console.log(this); //body對象
function fn(){
console.log(this); //Window
}
fn(); //函數加括號調用叫函數自執行,函數自執行時,內部的this指向頂層對象/window
};


三、對象方法調用時,this指向調用的對象

let obj = {
name : "lanlan",
fn : function(){
console.log(this);
},
lacy : {
name : "didi",
fn : function(){
let num = 10;
console.log(this);
}
}
};
obj.fn(); //obj
obj.dudu.fn(); //lacy


原文:https://blog.csdn.net/lan1977545649/article/details/83577080


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM