Letβs break down this keyword in JavaScript step by step, because it behaves differently depending on where and how it is used.
πΉ What is this?
thisis a special keyword in JavaScript that refers to the object that is currently executing the function.- Its value depends on how a function is called, not where it is defined.
πΉ Behavior of this in Different Scenarios
1. Global Context (non-strict mode)
console.log(this); // In browser β Window object
π In the global scope, this refers to the global object (window in browsers, global in Node.js).
In strict mode:
'use strict';
console.log(this); // undefined
2. Inside an Object Method
const person = {
name: "Himanshu",
greet: function () {
console.log(this.name);
}
};
person.greet(); // "Himanshu"
π Here, this refers to the object that owns the method (person).
3. Inside a Function
function show() {
console.log(this);
}
show(); // In browser β Window
π In normal functions, this refers to the global object (in non-strict mode).
π In strict mode, it becomes undefined.
4. Inside a Constructor Function
function Car(model) {
this.model = model;
}
const car1 = new Car("BMW");
console.log(car1.model); // "BMW"
π With new, this refers to the newly created object.
5. Inside a Class
class Student {
constructor(name) {
this.name = name;
}
showName() {
console.log(this.name);
}
}
const s1 = new Student("Ravi");
s1.showName(); // "Ravi"
π In a class, this refers to the instance of the class.
6. Arrow Functions
const obj = {
name: "Sharma",
greet: () => {
console.log(this.name);
}
};
obj.greet(); // undefined
π Arrow functions do not have their own this.
They inherit this from the surrounding scope (lexical scoping).
7. Event Handlers
button.addEventListener("click", function() {
console.log(this); // The button element
});
π With normal functions, this refers to the DOM element that received the event.
With arrow functions:
button.addEventListener("click", () => {
console.log(this); // Inherited from parent scope, usually Window
});
πΉ Quick Summary
- Global scope:
thisβ global object (window). - Object method:
thisβ object itself. - Function (strict mode):
thisβundefined. - Constructor / Class:
thisβ new object instance. - Arrow function:
thisβ parent scope. - Event handler (normal):
thisβ DOM element.
