Learn the concept
The this Keyword
The value of 'this' depends on how a function is called: in a method, it refers to the object; in a regular function, it's the global object (or undefined in strict mode); in arrow functions, it's lexically inherited from the enclosing scope.
'this' binding rules (in order of precedence):
new binding: When called with 'new', 'this' is the newly created object
Explicit binding: Using call(), apply(), or bind() explicitly sets 'this'
Implicit binding: When called as object method, 'this' is the object
Default binding: In non-strict mode, 'this' is global object; in strict mode, undefined
Arrow functions:
Common pitfalls:
// 1. Method call - 'this' is the object
const obj = {
name: 'Alice',
greet() {
console.log(this.name);
}
};
obj.greet(); // 'Alice'
// 2. Function call - 'this' is global/undefined
const greet = obj.greet;
greet(); // undefined (strict) or window.name
// 3. Constructor call - 'this' is new instance
function Person(name) {
this.name = name;
}
const bob = new Person('Bob');
console.log(bob.name); // 'Bob'
// 4. Arrow function - 'this' from lexical scope
const obj2 = {
name: 'Charlie',
greet: () => {
console.log(this.name); // 'this' from outer scope
}
};
obj2.greet(); // undefined (not obj2)Ensuring correct this binding in DOM event callbacks and React class components to access instance properties
Using return this in methods to enable chaining like builder.setName('x').setAge(25).build()
Understanding this in Vue options API, Backbone models, and other OOP frameworks that rely on this-based patterns
Build a query or config builder that uses return this for method chaining with a final build() method
Build a tool that demonstrates how this changes across different call styles (method, function, new, arrow, bind)