The 'this' Keyword
The this keyword is notoriously one of the most confusing parts of JavaScript. Unlike other languages where an equivalent keyword (like self in Python or this in Java) behaves strictly and predictably, JavaScript’s this changes depending on the context of how the code is executed.
Put simply, this refers to the execution context of the function it is used in. Let’s break down the common cases.
Global Context
Outside of any function, this refers to the global object.
- In a web browser, it refers to the
windowobject. - In a Node.js module, it refers to
module.exports.
// In a browser console
console.log(this); // Window { ... }
Note: If you activate “Strict Mode” by writing "use strict"; at the top of your file, this evaluates to undefined in the global scope.
Method Context
When used inside a standard object method, this intuitively refers to the object that the method was called on.
const myObject = {
message: "Hello, World!",
myMethod() {
console.log(this.message);
},
};
// Called upon myObject, so 'this' becomes myObject
myObject.myMethod(); // Output: "Hello, World!"
Arrow Functions
Arrow functions (which we will cover next) are a special case. They do not have their own this context at all. Instead, they inherit this from whatever parent scope they were defined in.