參考網站:
1. 函式的綁定物件 this 基礎
2. JavaScript 中的 function constructor 和關鍵字 new
this 代表函式的"綁定物件,通常在函式中使用
不同的程式碼脈絡下,綁定物件代表不同的東西
情況一:獨立的函式
1 2 3 4 5
| function test(){ console.log(this); console.log(this.innerWidth); } test();
|
情況二:物件的方法
1 2 3 4 5 6 7 8
| let obj={ x:3, test:function(){ console.log(this); console.log(this.x); } }; obj.test();
|
情況三:事件處理函式
1 2 3 4 5 6
| document.addEventListener("click",function(){ console.log(this);
this.body.innerHTML="已點擊"; });
|
情況四:建構函式
1 2 3 4 5 6 7 8
| function point(){ console.log(this); this.x=3; this.y=4; } let p1=new point(); console.log(p1);
|