JavaScript this Keyword: Complete Guide
Master the this keyword in JavaScript. Understand how this works in different contexts and arrow functions.
JavaScript this Keyword
What is 'this'?
`this` refers to the object that owns the function. It changes based on how the function is called.
``` ┌─────────────────────┐ │ Function Call │ └──────────┬──────────┘ │ ┌───────────▼───────────┐ │ 'this' points to │ │ the owner object │ └───────────────────────┘ ```
'this' in Different Contexts
### 1. In Methods (Object Functions)
```javascript const user = { name: 'John', greet: function() { console.log(`Hello, ${this.name}`); } };
user.greet(); // "Hello, John" // 'this' = user object ```
### 2. In Regular Functions
```javascript function showThis() { console.log(this); }
showThis(); // Window (in browser) or undefined (strict mode) ```
### 3. In Arrow Functions
```javascript const user = { name: 'John', greet: () => { console.log(this.name); // undefined // Arrow functions don't have their own 'this' } }; ```
Key Takeaway
`this` refers to the owner object. Changes based on how function is called. Arrow functions don't have their own `this`. Understanding `this` is crucial for object-oriented JavaScript.