JavaScript
/Intermediate
The 'this' Keyword
Definition
In JavaScript, the 'this' keyword refers to the object it belongs to. However, its value depends completely on HOW a function is called, not where it was defined.
Explain Like I'm New
Imagine the word 'this' as the word 'me' in English. If I say 'my name is AI', 'me' refers to the AI. If YOU say 'my name is John', 'me' refers to John. The meaning of 'this' changes depending on who is talking (or in code, which object is calling the function).
Real World Example
If a user clicks a button, and the button triggers a function, 'this' inside that function refers to the button that was clicked. It tells the function who caused it to run.
Common Use Cases
- •Accessing properties of an object from within its own methods
- •Creating reusable functions that can operate on different objects using call, apply, or bind
- •Handling events in the DOM
Interactive Example
Loading...
Console output will appear here...
Interview Questions
basic
- What does 'this' refer to in a regular object method?
- What does 'this' refer to in the global scope?
intermediate
- How do arrow functions handle the 'this' keyword differently?
- What is the difference between call, apply, and bind?
advanced
- How does 'new' binding work?
- What happens to 'this' when you pass an object method as a callback (e.g., to setTimeout)?
trick
- How can you manually set the value of 'this'?