The this keyword in JavaScript made simple.

You got this
  1. Outside of a function body, this points to the global object.
  2. Regular function calls use the global object as their execution context.
  3. Method calls use the calling object as their execution context.
  4. How this is bound depends on how a function is invoked rather than on where it’s defined.

Outside of a function

Inside of a function

Example

  • If this appears outside of the body of a function, it points to the global object.
  • Regular function calls use the global object as their execution context.

Using this in methods

  • Method calls use the calling object as their execution context.
  • You can’t tell the binding of this just by looking at the body of a function or method, you must look at how it is invoked.

Explicitly setting the context using call

Permanently binding an object

  • We can explicitly set the execution context using call or bind.
  • call invokes the function with its execution context set to the passed in argument.
  • bind returns a new function with the execution context permanently bound to the passed in argument.

Why arrow functions are special

Dealing with context loss using Arrow functions

Summary

  • Execution context refers to the value of the this keyword.
  • Outside of a function body, this points to the global object.
  • Regular function calls use the global object as their execution context.
  • Method calls use the calling object as their execution context.
  • In strict mode, this is implicitly set to undefined rather than the global object within regular function calls.
  • Arrow functions do not have their own execution context, they use the context of their surrounding scope.
  • You can’t tell the binding of this just by looking at the body of a function or method, you must look at how it is invoked.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store