this यो फङ्क्शन कहाँ परिभाषित छ भन्ने कुरा द्वारा होइन, बरु कसरी कल गरिएको छ भन्ने कुरा द्वारा निर्धारित हुन्छ। पाँच नियमहरू छन्:
js
obj = {
: ,
() { .; },
};
obj.();
f = obj.;
();
f.(obj);
();
this यो फङ्क्शन कहाँ परिभाषित छ भन्ने कुरा द्वारा होइन, बरु कसरी कल गरिएको छ भन्ने कुरा द्वारा निर्धारित हुन्छ। पाँच नियमहरू छन्:
obj = {
: ,
() { .; },
};
obj.();
f = obj.;
();
f.(obj);
();
Arrow functions को आफ्नै this हुँदैन — यो परिभाषित समयमा घेरिएको scope बाट अनुवांशिकता पाएको हुन्छ। यही कारणले नै 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 को रूपमा पास गर्दा आफ्नो बाइन्डिङ हराउन्छ, किनभने यो त्यस पछि सरल रूपमा कल हुन्छ:
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 लाई बन्द गर्नु हो।