Topic 35 of 37
Context (this)
Overview
The 'this' keyword in JavaScript is notoriously confusing. Unlike in Java or C++ where it always refers to the instance of the class, in JS, the value of 'this' depends entirely on HOW the function was called, not where it was written. This is called Execution Context.
Syntax
Arrow functions are the exception: they do NOT have their own 'this'. They inherit 'this' lexically from their parent scope.
The 4 of 'this'
javascript
// 1. Implicit Binding (Object Method)
const user = {
name: "Alice",
greet() { console.log(this.name); }
};
user.greet(); // "Alice" (this = user)
// 2. Explicit Binding (call, apply, bind)
function sayHi() { console.log(this.name); }
sayHi.call(user); // "Alice"
// 3. 'new' Binding (Constructor)
function Person(name) { this.name = name; }
const p = new Person("Bob"); // this = p
// 4. Default Binding (Global/Undefined)
const detachedGreet = user.greet;
// detachedGreet(); // TypeError in strict mode, or 'undefined' in loose modeCommon Pitfalls
- Using arrow functions for object methods. `const obj = { name: 'A', say: () => console.log(this.name) }` will NOT log 'A' because the arrow function inherits 'this' from the global window.
Interview Tips
- A classic trap: extracting a method from an object and passing it as a callback (e.g., `setTimeout(user.greet, 1000)`). It loses its context! You must use `.bind()` or an arrow function.
Real-World Example
Binding 'this' in React class components.
example
javascript
class Button extends React.Component {
constructor(props) {
super(props);
// Explicitly binding context so it isn't lost on click
this.handleClick = this.handleClick.bind(this);
}
}