Functions and this · core
How this is decided
For normal functions this is decided at call time by four rules in order — new, explicit call/apply/bind, a method call obj.fn(), then the default (undefined in strict mode, globalThis in sloppy mode) — while arrow functions take this from where they were written.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Order of rules: new > bind/call/apply > obj.method() > default binding.
- this depends on how the function is called, not where it is defined (arrows are the exception).
- Losing this: const f = obj.method; f() or passing obj.method as a callback (setTimeout, addEventListener, array.map) uses the default binding.
- Fixes: an arrow wrapper () => obj.method(), obj.method.bind(obj), an arrow class field, or the thisArg parameter of map/forEach.
- Class bodies and modules are strict, so an extracted class method gets this === undefined and throws TypeError when it reads a property.
- In a DOM listener added with addEventListener, a normal function's this is the element (same as event.currentTarget).
- Top level: this is window in a classic script, undefined in an ES module, and module.exports in a Node CommonJS file.
The red pen
Common traps: mistake → fix
Mistake: this is the object where the function was defined
Fix: it is decided by the call site.
Mistake: A bound function can be re-bound
Fix: the first bind wins; only new can override it.
Mistake: An arrow function in an object literal gets the object as this
Fix: it gets the enclosing function's this.
Easy to hard
Questions interviewers ask, easy to hard
- How is this decided? Give the rules in order of precedence.
- Why does passing obj.method to setTimeout lose this? Fix it three ways.
- What is this inside an arrow defined as a class field? Why did React class components use that pattern?
- What is this for fn.bind(a).bind(b)()? What happens with new on a bound function?
- What is this at the top level of a module vs a classic script vs a Node CommonJS file?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.