DEV Community

Cover image for JavaScript : The 'this' Keyword (English/Hindi)
Dharmik Dholu
Dharmik Dholu

Posted on

JavaScript : The 'this' Keyword (English/Hindi)

English

The 'this' keyword in JavaScript is a special identifier that refers to the current context or object in which it is used. Its value can change depending on how and where it is employed. Understanding 'this' is crucial for working effectively with JavaScript.

Let's look at an example to illustrate this concept:

// Example 1: 'this' in a Global Context
console.log(this); // 'this' refers to the global object (usually 'window' in browsers)

// Example 2: 'this' in a Function
function greet() {
  console.log(this); // 'this' inside a function can refer to the global object or be undefined in strict mode
}

greet();

// Example 3: 'this' in an Object Method
const person = {
  name: 'John',
  greet: function() {
    console.log(`Hello, my name is ${this.name}`);
  },
};

person.greet(); // 'this' refers to the 'person' object

// Example 4: 'this' in an Event Handler
const button = document.querySelector('button');
button.addEventListener('click', function() {
  console.log(this); // 'this' refers to the element that triggered the event (the button)
});
Enter fullscreen mode Exit fullscreen mode

Hindi

JavaScript mein 'this' keyword ek vishesh pehchanakar hai jo us vyakti ya vastu ko refer karta hai jiske samay mein yah istemal hota hai. Iska moolya istemal kiye jaane ke tarike aur sthal ke anurup badal sakta hai. 'this' ko samajhna JavaScript ke saath prabhavit rup se kam karne ke liye mahatvapurn hai.

Chaliye ek udaharan dekhe is siddhant ko spasht karne ke liye:

// Udaharan 1: 'this' Global Samay Mein
console.log(this); // 'this' sadharan roop se global vastu ko refer karta hai (aam taur par browser mein 'window' hota hai)

// Udaharan 2: 'this' Ek Function Mein
function greet() {
  console.log(this); // Ek function ke andar 'this' global vastu ko refer kar sakta hai ya strict mode mein undefined ho sakta hai
}

greet();

// Udaharan 3: 'this' Ek Object Method Mein
const vyakti = {
  naam: 'John',
  greet: function() {
    console.log(`Namaste, mera naam hai ${this.naam}`);
  },
};

vyakti.greet(); // 'this' 'vyakti' object ko refer karta hai

// Udaharan 4: 'this' Ek Ghatna Handler Mein
const button = document.querySelector('button');
button.addEventListener('click', function() {
  console.log(this); // 'this' us tatva ko refer karta hai jo ghatna ko trigger kiya (button)
});
Enter fullscreen mode Exit fullscreen mode

Isse 'this' keyword ke mahatva ko samajhna aapko JavaScript mein prabhavit rup se kaam karne mein madad karega.

Top comments (0)