This
A JavaScript keyword that refers to the object that is executing the current function, with its value determined by how a function is called.
Overview
The 'this' keyword is one of the most misunderstood concepts in JavaScript. Its value is determined by the execution context - how a function is called rather than where it is defined. Understanding 'this' is crucial for object-oriented programming in JavaScript and avoiding common bugs.
Example
javascript// Object method const person = { name: 'Alice', greet() { console.log(`Hello, I'm ${this.name}`); } }; person.greet(); // "Hello, I'm Alice" // Arrow functions don't have their own 'this' const obj = { name: 'Bob', regular: function() { console.log(this.name); // 'Bob' }, arrow: () => { console.log(this.name); // undefined (lexical 'this') } }; // Explicit binding const greet = person.greet.bind(person); greet(); // Still works
Key Points
- Value depends on how function is called
- In methods: refers to the object
- In regular functions: refers to global object (or undefined in strict mode)
- Arrow functions inherit 'this' from parent scope
- Can be explicitly set with bind(), call(), apply()
Learn More
- Arrow Function - Arrow functions
- Closure - Closures
- MDN: this