DEV Community

Discussion on: Take 'this' Quiz, Understand How 'this' Works in JavaScript

Collapse
 
z2lai profile image
z2lai • Edited

It's good to practice 'this' like this but there's always a whole bunch of other scenarios that might still trip people up. The best thing to do is to have some theory to solidify the understanding:

  1. 'this' is an object created for every Execution Context that is created (on program startup and on every function invocation).
  2. 'this' can change based on how/where the function is called/invoked.
  3. There are four patterns of invoking functions that define the context of the function being called:
  • function invocation (e.g. says())
  • method invocation (e.g. call.says())
  • constructor invocation pattern (when you call a constructor function with the 'new' keyword - e.g. var person = new Caller())
  • apply invocation pattern (when you provide your own context while calling the function with say.call() or say.apply(), or if you explicitly bind the context with say.bind()) Here's a really good article about these four patterns (read until the React part): reactkungfu.com/2015/07/why-and-ho...
Collapse
 
liaowow profile image
Annie Liao

Couldn't agree more. Thanks so much for providing an overarching concept around 'this'. That could've been a better opening for 'this' post (pun intended).

Collapse
 
leewhite98 profile image
LeeWhite98

1) 'this' is an object created for every Execution Context that is created (on program startup and on every function invocation).

I think it's also important to mention that arrow functions don't get own this keyword - they can use this keyword of their closest regular function parent