this Binding Rules, Fully in JavaScript
this binds by call shape, completely: method calls (obj.f()) bind the receiver; bare calls bind undefined (strict) or global (sloppy); new binds the fresh instance; call/apply/bind set it explicitly; arrows ignore all of it (lexical). Four-plus-one rules predict every case β this confusion is always a call-shape question in disguise.
Callbacks lose receivers (setTimeout(obj.method) detaches), classes in strict mode crash loudly on detachment (better than silent globals), and bound copies (method.bind(this) in constructors) freeze receivers for event systems. Master the five shapes and this becomes deterministic.
Method calls bind receivers
obj.f() sets this to obj β the only rule most code ever needs.
Bare calls bind nothing useful
f() gives undefined (strict) β detached methods and callbacks land here by accident.
new binds fresh instances
new F() sets this to the new object β constructors rely on exactly this rule.
Arrows opt out entirely
Arrow this is lexical, immune to call shape β callbacks preserving outer receivers, methods breaking when misused.
let obj = { name: "Ada", hi() { return "hi " + this.name; }, later: null,};obj.later = obj.hi;console.log(obj.hi());try { let f = obj.hi; f();} catch (e) { console.log("detached:", e instanceof TypeError);}Recommended resourcesAffiliate links Β· may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself β building beats watching.