Reading — step 1 of 7
Learn
this is the most-misunderstood concept in JavaScript. Get it right and the rest of OOP-style JS makes sense. Get it wrong and you'll spend hours debugging methods that mysteriously fail.
The single most important rule: this is determined by HOW a function is called, not WHERE it's defined.
The classic surprise
Same function. Different call site. Different this. The line const fn = user.greet doesn't "copy the method" — it just grabs a reference. Calling fn() is a plain function call; the connection to user is gone.
The four rules of this
For regular functions, this follows one of four rules — picked by HOW the function was called:
1. Method call → this is the object before the dot
2. Plain function call → this is undefined (strict mode) or global
In strict mode and ES modules, plain calls produce undefined. (Old non-strict mode used the global object.)
3. new call → this is a brand-new object
4. Explicit binding → this is whatever YOU pass
call(thisArg, ...args)— invoke immediately with thatthis.apply(thisArg, [args])— same as call but args as array.bind(thisArg)— returns a NEW function that's permanently bound. Doesn't invoke.
Arrow functions — they DON'T have their own this
This is the killer feature for callbacks. Arrow functions inherit this from the surrounding scope — like a closure:
With a regular function as the setTimeout callback, this would be undefined — because setTimeout calls it as a plain function. Arrows fix this by inheriting.
Common bugs
Lost this from method extraction:
Fix: bind it: const greet = user.greet.bind(user).
Lost this in event handlers:
Fix: use an arrow method (class fields), or bind in constructor:
Using arrow as object method when you NEED this:
Fix: use method shorthand greet() { ... }.
Quick reference
| Call form | this is |
|---|---|
obj.fn() | obj |
fn() (plain) | undefined (strict) / global |
new Fn() | new object |
fn.call(x) / apply / bind | x |
| Arrow function | inherited (lexical) |
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…