JavaScript

Understanding 'this' in JavaScript

JavaScript code highlighting the 'this' keyword
Understanding 'this' in JavaScript
The 'this' keyword in JavaScript is notoriously confusing because its value depends on how the function is called. In the global context, this refers to the window object (in browsers). Inside a method (an object function), this refers to the object the method belongs to. However, inside a regular function (not an arrow function or method), this defaults to the global object (or undefined in strict mode). This trips people up inside event listeners or callbacks. Arrow functions changed the game: they do not have their own 'this'; they inherit it from the enclosing scope (lexical scoping). This makes them perfect for callbacks. For example, inside a class method, if you use a regular function for a setTimeout callback, this will be window. If you use an arrow function, this will be the class instance. Understanding this binding is essential before moving to frameworks like React.
3,864
Views
146
Words
1 min read
Read Time
May 2025
Published
← All Articles 📂 JavaScript