🪟 The this
Keyword in JavaScript
Understanding the this
keyword is essential for mastering JavaScript, as its value changes depending on how and where it is used. Let's break down its behavior in different contexts.
Global Context
Let’s start with an empty JS file. Even if there's no code, when you run the file:
- The JavaScript engine creates a Global Execution Context (GEC).
- A global object, called
window
in browsers, is created. - The
this
keyword is initialized to refer to this global object.
Open the browser console and type:
Explanation:
In the browser, the global object is named window
. All globally declared functions and variables become properties of window
. The this
keyword, when used in the global scope, also refers to the window
object.
What Is the "Global Space"?
Any variable or function declared outside of any function or block resides in the global space. For example:
index.js | |
---|---|
All the following refer to the same value in the global scope:
index.js | |
---|---|
Summary: How Does this
Work?
- In the global scope (browser):
this
refers towindow
. - In Node.js:
this
refers to theglobal
object. - Inside an object’s method:
this
refers to the object itself. - Inside a function (non-strict mode):
this
refers to the global object. - Inside a function (strict mode):
this
isundefined
. - Arrow functions:
this
is lexically scoped and inheritsthis
from the parent scope. - DOM event handlers:
this
refers to the HTML element that triggered the event.
Examples
Global Scope
Inside a Function
Inside an Object Method
Method Borrowing with call, apply, bind
Inside an Arrow Function
Tip
Arrow functions do NOT have their own this
; they inherit this
from where they are defined.
Nested Arrow Functions
this
is inherited from its parent scope, which is the method where this
refers to obj2
.
this
in DOM Event Handlers
Quick Reference
- By default,
this
refers to the global object (window
in browsers,global
in Node.js). - Inside an object method,
this
refers to the object. - In arrow functions,
this
is inherited (lexical). - In DOM event handlers,
this
is the element on which the handler is placed. - In strict mode,
this
inside functions (not called as a method) isundefined
.
Tip
An empty JS file is the shortest possible JS program, since it still sets up the global context (window
, this
, etc.).