this vendoset sipas MËNYRËS SË QË një funksion THIRRET, jo sipas vendit ku përkufizohet. Ka pesë rregulla:
js
obj = {
: ,
() { .; },
};
obj.();
f = obj.;
();
f.(obj);
();
this vendoset sipas MËNYRËS SË QË një funksion THIRRET, jo sipas vendit ku përkufizohet. Ka pesë rregulla:
obj = {
: ,
() { .; },
};
obj.();
f = obj.;
();
f.(obj);
();
Funksionet arrow nuk kanë this të tyre — ato e trashëgojnë atë nga hapësira përreth në kohën e përkufizimit. Kjo është arsyeja pse arrow-et janë perfekte për callback-et:
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); });
},
};
Përcjellja e një metode si callback humbet lidhjen e saj, sepse atëherë thirret në mënyrën e zakonshme:
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
Mospërfaqimi i this është një nga gabimet më të zakonshme në JS.
Zgjidhja zakonisht është një funksion arrow ose .bind() për të bllokuar this-in e synuar.