0%

200205-學習紀錄 函式的綁定物件this基礎

參考網站:

1. 函式的綁定物件 this 基礎
2. JavaScript 中的 function constructor 和關鍵字 new



this 代表函式的"綁定物件,通常在函式中使用 不同的程式碼脈絡下,綁定物件代表不同的東西

情況一:獨立的函式

1
2
3
4
5
function test(){
console.log(this); //this就是 window 物件
console.log(this.innerWidth); //印出視窗的寬度
}
test();

情況二:物件的方法

1
2
3
4
5
6
7
8
let obj={
x:3,
test:function(){
console.log(this); //this就是方法所屬的物件本身
console.log(this.x);//印出物件的屬性 x
}
};
obj.test();

情況三:事件處理函式

1
2
3
4
5
6
document.addEventListener("click",function(){
console.log(this);
/*this 就是觸發事件的對象物件
例如在按鈕上註冊click物件 this就是代表那個按鈕 */
this.body.innerHTML="已點擊"; //舉例用法 點擊網頁會跳出"已點擊" 文字
});

情況四:建構函式

1
2
3
4
5
6
7
8
function point(){
console.log(this);
/*this就是瀏覽器自動幫我們新建立好的空白物件 顯示為point{}*/
this.x=3;
this.y=4;
}
let p1=new point();
console.log(p1); //結果為point{x:3,y:4}