r/learnjavascript • • Feb 17 '26

this keyword learning

this keyword in javascript is very confusing especially during interviews. Everytime, its very confusing to understand and easily to forget.

What would be the best resource to learn this?

4 Upvotes

17 comments sorted by

View all comments

Show parent comment

2

u/delventhalz Feb 18 '26

(1) Except when a super constructor returns a different object.

Seems like a distinction without a difference. The super call makes this an instance of the Base class sure, but it is still the object which will be returned by the Derived constructor.

(3) Except in ES modules where it is undefined and CJS modules where its the exports object.

...oof. Well, it was news to me that ES modules have a different root-scope this than strict mode and CJS modules have a different root-scope this than the Node console. So the complete (?) list of possible root-scope this values would be:

  1. window (browser console, vanilla JS files run in browser, including when in strict mod)
  2. global (Node console)
  3. undefined (ES modules)
  4. exports (CJS modules)

(4) Except when the function is... an unqualified method called within a with block

Fair enough. I studiously avoid thinking about with blocks, but they maybe should have gotten their own entry above. If I had described this more conceptually (i.e. "the object the method is called on"), a with block would be self-explanatory, but of course I decided to focus on how the literal code looks, and with does indeed change the way the code is written.