QuestionsJavaScript

How does this work?

this bindingEasyJavaScript

Explain the rules that determine `this`. Why do arrow functions behave differently?

What it tests

The four binding rules and the arrow-function exception — a top source of real bugs.

Approach & answer

`this` is determined by HOW a function is called, not where it's defined: (1) new binding — new Fn() gives the new object; (2) explicit — call/apply/bind set it; (3) implicit — obj.method() gives obj; (4) default — a standalone call gives undefined (strict) or the global object. Arrow functions ignore all four: they capture `this` lexically from the enclosing scope, which is why they are ideal for callbacks inside methods (no more const self = this). The precedence when several rules could apply, highest to lowest: new > explicit (bind/call/apply) > implicit (method call) > default. So a bound function beats a later method call, and `new` beats even bind. The single most common bug this causes: passing obj.method as a callback (setTimeout(obj.method), onClick={obj.method}) strips the implicit receiver, so `this` falls back to default — fix with obj.method.bind(obj) or an arrow wrapper () => obj.method(). Arrow functions have no `this`, `arguments`, or `prototype` of their own, so they can't be constructors.

Use this technique when

Losing `this` when passing a method as a callback — bind it or wrap in an arrow. Never use an arrow for an object method that needs its own `this`.

References

js