Skip to content
this and Methods
step 1/7

Reading — step 1 of 7

Learn

~3 min readObjects in Depth

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

js

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

js

2. Plain function call → this is undefined (strict mode) or global

js

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

js

4. Explicit binding → this is whatever YOU pass

js
  • call(thisArg, ...args) — invoke immediately with that this.
  • 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:

js

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:

js

Fix: bind it: const greet = user.greet.bind(user).

Lost this in event handlers:

js

Fix: use an arrow method (class fields), or bind in constructor:

js

Using arrow as object method when you NEED this:

js

Fix: use method shorthand greet() { ... }.

Quick reference

Call formthis is
obj.fn()obj
fn() (plain)undefined (strict) / global
new Fn()new object
fn.call(x) / apply / bindx
Arrow functioninherited (lexical)

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…