this ఫంక్షన్ ఎలా పిలువబడుతుంది అనే దానిపై ఆధారపడి ఉంటుంది, ఇది ఎక్కడ నిర్వచించబడిందో కాదు. ఐదు నియమాలు ఉన్నాయి:
js
obj = {
: ,
() { .; },
};
obj.();
f = obj.;
();
f.(obj);
();
this ఫంక్షన్ ఎలా పిలువబడుతుంది అనే దానిపై ఆధారపడి ఉంటుంది, ఇది ఎక్కడ నిర్వచించబడిందో కాదు. ఐదు నియమాలు ఉన్నాయి:
obj = {
: ,
() { .; },
};
obj.();
f = obj.;
();
f.(obj);
();
Arrow functions తమ స్వంత this లేదు — అవి నిర్వచన సమయంలో చుట్టుపక్కల నుండి దీనిని కారణమవుతాయి. ఇదే కారణంగా 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); });
},
};
ఒక పద్ధతిని callback గా పంపడం దాని బైండింగ్ను కోల్పోతుంది, ఎందుకంటే ఇది సరళంగా పిలువబడుతుంది:
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 ను లాక్ చేయడం.