What is this?
this is a special keyword that refers to the object that is currently executing the function. Its value depends on how and where the function is called, not where it's defined.
π‘ Key insight
this is determined at call time, not definition time. This is the source of most confusion.
Rules for this
- Global context:
thisrefers to the global object (window in browsers) - Object method:
thisrefers to the object the method was called on - Arrow functions:
thisis inherited from the surrounding scope - Event handlers:
thisrefers to the element
Examples
// Global context
console.log(this); // window (in browser)
// Object method
let person = {
name: "Alice",
greet: function() {
console.log(this.name);
}
};
person.greet(); // "Alice"
// Arrow function (inherits parent's this)
let obj = {
name: "Bob",
greet: () => {
console.log(this.name); // this is from outer scope
}
};
Common Mistakes
- Assuming
thisin arrow functions works like regular functions - Losing
thiswhen passing methods as callbacks - Using
thisin global scope expecting it to be something else
Quick Quiz
1. What does this refer to in a method of an object?
2. How does this behave in arrow functions?
3. When is this determined?
Summary
thisdepends on how the function is called- In object methods,
thisrefers to the object - Arrow functions inherit
thisfrom the surrounding scope - Use
call()andapply()to explicitly setthis - Be careful with
thisin callbacks
