this इस बात से तय होता है कि किसी function को कैसे CALL किया जाता है, न कि वह कहाँ define किया गया है। इसके पाँच नियम हैं:
js
obj = {
: ,
() { .; },
};
obj.();
f = obj.;
();
f.(obj);
();
this इस बात से तय होता है कि किसी function को कैसे CALL किया जाता है, न कि वह कहाँ define किया गया है। इसके पाँच नियम हैं:
obj = {
: ,
() { .; },
};
obj.();
f = obj.;
();
f.(obj);
();
Arrow functions का अपना कोई this नहीं होता — वे define होने के समय enclosing scope से इसे inherit करते हैं। यही कारण है कि arrows callbacks के लिए एकदम उपयुक्त हैं:
const obj = {
items: [1, 2],
logAll() {
// ✅ arrow inherits `this` from logAll → `this` is obj
this.items.forEach(i => console.log(this.items, i));
// ❌ a regular function here would have its own `this` (undefined) → crash
// this.items.forEach(function (i) { console.log(this.items); });
},
};
किसी method को callback के रूप में pass करने से उसकी binding खो जाती है, क्योंकि तब उसे plainly call किया जाता है:
button.addEventListener("click", obj.getX); // ❌ `this` is the button
button.addEventListener("click", () => obj.getX()); // ✅ keeps obj
button.addEventListener("click", obj.getX.bind(obj)); // ✅ also fine
this को गलत समझना JS की सबसे आम बगों में से एक है।
इसका समाधान आमतौर पर एक arrow function या .bind() होता है, ताकि इच्छित this lock हो जाए।