Initialize & Access Class Fields in JavaScript

JavaScript·2 min read·Jan 1, 2025

In JavaScript, classes are not only used to store data through fields or to provide utility collections through methods. They are also meant to define behavior through them.

In practice, many methods need to read or update the fields of the object they belong to. For example, a method may validate a value before storing it, compute a result from existing fields, or update multiple fields at once to keep the object consistent.

This is why classes provide a way for their own methods to access the fields and other methods of the same object from within the class.

The this keyword

When used within a class method, the this keyword refers to the current instance of the class, allowing you to access and modify its properties and invoke its methods.

class ClassName {  field;  methodA() {    this.field = value;  }  methodB() {    this.methodA();  }}

💡 When using the this keyword to set the value of inexistent class field, this field will be automatically added to the instance.

Unlock the program 🚀

Pay once, own it forever.

€79

30-day money-back guarantee

  • 13 modules
  • 113 lessons with full-code examples
  • 29 projects with commented solutions
  • All future lesson and project updates
  • Lifetime access

By submitting this form, you agree to the Terms & Conditions and Privacy Policy.