--- tags: JavaScript --- # This 到底是啥毀 > This is the object that is executing the current function. `this` 為執行當下 function 的物件,在不同位置,分別會代表不同的值。 - 在 **global context** 下 this 代表 **window object**。 - 在 **function context** 下: - Normal function,function 被直接執行、沒有對象 call function、沒有使用 strict,this 代表 **window object**。 ```javascript function func () { console.log(this) // [object Window] } func() ``` ```javascript function func() { 'use strict' console.log(this) // undefined } func() ``` - 在 event handler 中被執行,this 代表 **Event Target**,也就是事件目標的 DOM。 ```javascript function func () { console.log(this) } const targetBtn = document.getElementById('targetBtn') targetBtn.addEventListener('click', func) // <button id="targetBtn"></button> ``` - Object function,this 代表 `該 Object`。 ```javascript let person = { name: 'Celine', greet: function () { console.log(`I'm ${this.name}`) } } person.greet() // I'm Celine ``` 但此時若用 arrow function,此時 `this` 代表 `window object` ,蝦毀 Orz... 因為 this 在不同的 function scope 內會被重新定義,而這個 arrow function 實際上是 window 的 method,所以此時 this 就代表 `window object` 。