HomeJAVASCRIPTExplain this keyword in JavaScript.

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?

  • this is 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.

Share:Β 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *