Demystify the this keyword, implicit binding, explicit call/apply/bind rules, and arrow function lexical binding behaviors.
Learn how variables act as labeled containers for data using const, let, and var to manage lexical scope and reassignment safely in modern applications.
In JavaScript, the this keyword refers to an object context, but which object depends on how the function was invoked at runtime!
Losing this context inside event handlers or async callbacks is a frequent bug when object methods are detached.
this Bindingobj.method()) -> this refers to obj.fn.call(obj), fn.apply(obj), or fn.bind(obj).new Constructor() -> this refers to the newly instantiated object.this. They inherit this lexically from their outer parent scope!const user = {
name: "Maria",
greet() {
console.log(`Hi, I am ${this.name}`);
},
};
user.greet(); // "Hi, I am Maria" (Implicit)
const detachedGreet = user.greet;
detachedGreet(); // "Hi, I am undefined" (Lost context!)
// Explicit Fix using .bind()
const boundGreet = user.greet.bind(user);
boundGreet(); // "Hi, I am Maria"
thisArrow functions capture this from their enclosing lexical context:
const timer = {
seconds: 0,
start() {
setInterval(() => {
this.seconds++; // Inherits 'this' from timer object!
console.log(this.seconds);
}, 1000);
},
};
this to point to the object, because arrow functions capture outer global this!Always check how the function was invoked. Next, let's learn how the V8 Event Loop handles Microtasks vs Macrotasks!