JavaScript
Context
Context (execution context) is the value pointed to by the
thiskeyword 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 —
thisdoes not point to variables from the lexical environment.
Context Types
-
Global Context
When code runs outside a function —
thispoints to the global object (windowin the browser,globalin Node.js). -
Function Context
- Regular call:
this=undefined(in strict mode) or the global object. - Method call:
thisrefers to the object.
- Regular call:
-
Constructor Context
When using
new,thispoints to the new object instance. -
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 fixthis. - Proper context management is critical when working with classes, event handlers, and object methods.