this confuses everyone because it is decided at call time, not write time. Four rules cover every case.
The four rules (in priority order)
- new:
new Fn()→ this = the new object - Explicit:
fn.call(obj)/apply/bind→ this = obj - Method call:
obj.fn()→ this = obj (whatever is left of the dot) - Default: plain
fn()→ undefined in strict mode (window otherwise)
The classic bug
const user = {
name: "Ravi",
greet() { console.log(this.name); }
};
user.greet(); // "Ravi" — rule 3
const g = user.greet;
g(); // undefined — rule 4, the dot is gone!
setTimeout(user.greet, 100); // same bug
setTimeout(() => user.greet(), 100); // ✅ fixedArrow functions — the exception
Arrows have no own this — they inherit it from where they were written. Perfect for callbacks, wrong for object methods.
Drill this with the JS interview questions — it appears in nearly every set.
← All Articles