Initialize & Access Class Fields in JavaScript

8 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.

Example

Let's consider this script:

class Book {
  title;

  setInfo(title, author) {
    this.title = title;
    this.author = author;
  }

  getInfo() {
    console.log(`${this.title}, written by ${this.author}.`);
  }
}

let book = new Book();

book.setInfo('1984', 'George Orwell', 328);
book.getInfo();

When executed, it will:

  1. Define a Book class that implements:

    • A title field that's undefined.
    • A setInfo() method that updates the value of the title property and initializes a new author property.
    • A getInfo() method that outputs the value of the properties of the class instance.
  2. Define a book variable and initialize it with an instance of the Book class.

  3. Execute the setInfo() method of the book instance.

  4. Execute the getInfo() method of the book instance.

Which will produce this output:

1984, written by George Orwell.

The constructor method

The class constructor method is a special method that is automatically executed by the class when a new instance of that class is created.

Its main purpose is to initialize the properties of the resulting instance, and set up any initial configuration or behavior.

class ClassName {
  constructor(param1, ..., paramN) {
    //
  }
}

The arguments of the constructor() method are defined when creating the instance:

let object = new ClassName(param1, ..., paramN);

Notes:

  • 💡 The constructor method doesn't need to return a value.
  • ⚠️ A class cannot have more than one constructor method.

Example

Let's consider this script:

class Book {
  constructor(bookTitle = 'Untitled', bookAuthor = 'Unknown') {
    this.title = bookTitle;
    this.author = bookAuthor;
  }
}

const book1 = new Book('1984', 'George Orwell');
const book2 = new Book();

console.log(`${book1.title} written by ${book1.author}`);
console.log(`${book2.title} written by ${book2.author}`);

When executed, it will

  1. Define a new class named Book that implements:

    • Two properties named title and author.
    • A constructor() method used to initialize these properties upon instantiation.
  2. Declare a variable named book1 that contains an instance of the Book class initialized with user-defined values.

  3. Declare a variable named book2 that contains an instance of the Book class initialized with default constructor values.

Which will produce this output:

1984, written by George Orwell
Untitled, written by Unknown

Enjoying the courses?

I've made these courses completely free so anyone can learn from them. If they've helped you and you'd like to actively support the work behind BackendBrewery, you can leave a tip:

Support BackendBrewery
Initialize & Access Class Fields in JavaScript | Backend Brewery