Skip to content

Instantly share code, notes, and snippets.

@ivankisyov
Last active December 29, 2018 16:40
Show Gist options
  • Save ivankisyov/af8a6ee19c8920f250e289b43a4f7dfb to your computer and use it in GitHub Desktop.
Save ivankisyov/af8a6ee19c8920f250e289b43a4f7dfb to your computer and use it in GitHub Desktop.
This in JS

This in JS

How to determine what this refers to:

1. Check where the function is being called! Then:

  • Is there a dot and an object preceding that dot. If yes, this will refer to that object
  • Is call or apply or bind used. If yes, this will refer to the first argument which was passed to those methods
  • Do you see the usage of the new keyword. If so, this will refer to the newly created object
  • Is this inside an arrow function. If yes, this will refer to the this of the parent function. Check the parent/enclosing scope
  • If none from above, this will refer to the global object. If in strict mode, this will be undefined

One of the best articles on the topic:

Understanding the "this" keyword, call, apply, and bind in JavaScript

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment