Dmytro Morar
JavaScript

Context

Context (execution context) is the value pointed to by the this keyword during code execution.

Context defines the owner object within which the function was called and is set dynamically at call time.

Context vs Scope

  • Scope is defined at function declaration (lexically).
  • Context is set at function call (dynamically).
  • Context is not related to scope — this does not point to variables from the lexical environment.

Context Types

  1. Global Context

    When code runs outside a function — this points to the global object (window in the browser, global in Node.js).

  2. Function Context

    • Regular call: this = undefined (in strict mode) or the global object.
    • Method call: this refers to the object.
  3. Constructor Context

    When using new, this points to the new object instance.

  4. Manual Context Control

    Context can be explicitly set using call(), apply(), bind().

Key Ideas

  • Context describes the binding of a function to an object at the moment of invocation.
  • Defined dynamically, unlike scope.
  • When context is lost (e.g., passing a method as a callback), bind() can be used to fix this.
  • Proper context management is critical when working with classes, event handlers, and object methods.

On this page