Explain this keyword in JavaScript.
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.
No comments yet! You be the first to comment.
