How does 'this' work in different contexts?
💡 Hint: Determined by how a function is called, not where it is defined
this is determined by how a function is called:
- Global → window / undefined (strict)
- Method call → the object before the dot
- new → the newly created object
- call/apply/bind → whatever you pass
- Arrow function → outer lexical scope
- Event listener → the element that fired
const obj = { val: 42, getVal() { return this.val; } };
const fn = obj.getVal;
fn(); // undefined — lost context!
fn.call(obj); // 42 — restored