## Notes
In arrow functions, `this` is *lexically bound*, which means it takes the value of `this` in the surrounding context, not where it is called.
In a regular function, `this` is bound based on the object it is attached to.
## Regular Functions
Regular functions define their own context for `this` based on how they are called.
### Method Context
`this` refers to the object that owns the method
```javascript
const obj = {
name: "Object",
getName: function() {
return this.name;
}
};
console.log(obj.getName()); // Object
```
### Standalone Context
```javascript
function showThis() {
console.log(this)
}
showThis();
/*
Object [global] {
global [Circular *1],
clearInterval: [Function: clearInterval],
clearTimeout: [Function: clearTimeout],
setInterval: [Function: setInterval],
...
}
*/
```
### Dynamic Binding
Regular functions allow `this` to be set using methods like `call`, `apply`, `bind`
```javascript
// Regular function
function greet() {
console.log(`Hello, my name is ${this.name}`);
}
// object with a name property
const person = {
name: 'Dale'
}
// Using call to explicitly set the value of `this`
greet.call(person)
// Using apply (similar to call, but also accepts array)
greet.apply(person);
// use bind to explicitly set the value of `this` and return a new function
const greetings = greet.bind(person)
greetings();
```
## `this` In Arrow Functions
### Lexical Scoping
```javascript
const obj = {
name: "Object",
getName: () => this.name
}
console.log(obj.getName()) // undefined
```
It's undefined because `this` is determined by the context in which the function is called (globally), and the arrow function does not bind its own `this`.
### Callbacks
```javascript
function Timer() {
this.seconds = 0;
setInterval(() => {
this.seconds++;
console.log(this.seconds);
}, 1000)
}
const timer = new Timer();
```
The lexical scope is inside `Timer`, so the arrow function has access to `this.seconds`.
## References
- [[JavaScript Study MOC]]
- [This Keyword in Arrow Functions and Regular Functions - Geeks for Geeks](https://www.geeksforgeeks.org/javascript/behavior-of-arrow-functions-and-regular-functions-for-this-keyword/)