Do you know how it works? - The "this" keyword

TL;DR: In JavaScript, the value of this depends entirely on how a function is called, not where it was defined. It can reference the global object (window/global), the calling object, undefined (in strict mode), or be explicitly bound using .bind(), .call(), or arrow functions. In this post, we cover: What this points to in different contexts: object methods, global scope, functions, classes, and callbacks How this behaves differently in strict mode The use of .bind() and .call() to control this explicitly Why arrow functions can be lifesavers in callback scenarios How this works with constructor functions and classes By the end, you’ll understand the most misunderstood keyword in JavaScript with clarity. Introduction The question that could bring world peace: "What is the value of this?" If you’ve worked with JavaScript for a while, you’ve probably hit this dreaded error: Cannot read property 'value' of undefined If you haven’t seen it yet — don’t worry young padawan, your time will come.

May 5, 2025 - 15:32
 0
Do you know how it works? - The "this" keyword

TL;DR:
In JavaScript, the value of this depends entirely on how a function is called, not where it was defined.
It can reference the global object (window/global), the calling object, undefined (in strict mode), or be explicitly bound using .bind(), .call(), or arrow functions.
In this post, we cover:

  • What this points to in different contexts: object methods, global scope, functions, classes, and callbacks
  • How this behaves differently in strict mode
  • The use of .bind() and .call() to control this explicitly
  • Why arrow functions can be lifesavers in callback scenarios
  • How this works with constructor functions and classes By the end, you’ll understand the most misunderstood keyword in JavaScript with clarity.

Introduction

The question that could bring world peace: "What is the value of this?"
If you’ve worked with JavaScript for a while, you’ve probably hit this dreaded error:

Cannot read property 'value' of undefined

If you haven’t seen it yet — don’t worry young padawan, your time will come.