Class Fields: A New Feature for Handling Members in JavaScript Classe

07 April 2023 Alejandro Acosta

Class Fields: A New Feature for Handling Members in JavaScript Classes

JavaScript developers are excited about the new Class Fields proposal, which introduces several improvements for handling members on JavaScript classes. This umbrella proposal includes public and private instance fields, private instance methods and accessors, and static class features. In this post, we’ll focus on public and private instance fields.

Before the Class Fields proposal, developers would declare a member field inside the class keyword by introducing it in the constructor. Now, the latest ECMAScript specification allows developers to define the member field inline as part of the class body.

Here's an example of inline public and private class fields:

class Song {

  title = "";

  #artist = "";

  constructor(title, artist){

   this.title = title;

   this.#artist = artist;

  }

}

let song1 = new Song("Only a Song", "Van Morrison");

console.log(song1.title); // outputs “Only a Song”

console.log(song1.artist); // outputs undefined

In this example, we define a class, Song, with two members, title and artist. The artist member is prefixed with a hashtag (#) symbol, so it is private. We allow for setting these fields in the constructor. Note that the constructor must access this.#artist with the hash prefix again; otherwise, it would overwrite the field with a public member.

Next, we define an instance of the Song class, setting both fields via the constructor. We then output the fields to the console. The point is that song1.artist is not visible to the outside world and outputs undefined. Even song1.hasOwnProperty("artist") will return false. Additionally, we cannot create private fields on the class later using assignment.

Overall, this is a nice addition to JavaScript, making for cleaner code. Most browsers have supported public and private instance fields for a while, and it’s great to see them officially incorporated.

What are your thoughts on the Class Fields proposal? Do you think it will make your code cleaner and more organized? Let us know in the comments below, and if you want to be prepared for questions about Class Fields in your next interview, leave a comment with the word "interview."

#interview #javascript