Google’s V8 7.2 and Chrome 72 gets public class fields syntax; private class fields to come soon

2 min read

Yesterday, Google announced that they are introducing the public class fields in V8 7.2 and Chrome 72 and will be shipping the private class fields soon. These new class fields syntax were introduced by Daniel Ehrenberg and Jeff Morrison in a proposal to ECMA TC39 called Class field declarations for JavaScript, which is in stage 3 now.

As per the proposal, declaring fields up-front will ensure that the instances go through fewer state transitions and the class definitions will become more self-documenting.

Public class fields

The public class fields syntax aims to simplify the class definition. This will also eliminate the need of constructor just to define some fields. Here’s how you can implement a class as per this syntax:

class IncreasingCounter {
 _count = 0;
 get value() {
   console.log(‘Getting the current value!’);
   return this._count;
 }
 increment() {
   this._count++;
 }
}

Private class fields

A field in JavaScript is marked as private using _. This makes the field hidden by convention, but in fact, it is fully public. To make the fields private we can mark them with #, which means that they will not be accessible outside of the class body.

class IncreasingCounter {
 #count = 0;
 get value() {
   console.log(‘Getting the current value!’);
   return this.#count;
 }
 increment() {
   this.#count++;
 }
}

Though in JavaScript, there is a need for some kind of mechanism to provide private or controlled access beyond closures, this proposal seems very sloppy as some developers believe. One of the Hacker News users said, “This syntax is…odd. It is not expressive and comes off as a “language hack.” The only people who would understand it are those who happen to stumble on this article.

Read more in detail on Google Developers and also check out the proposal on GitHub.

Read Next

4 key findings from The State of JavaScript 2018 developer survey

Why use JavaScript for machine learning?

V8 JavaScript Engine releases version 6.9!

Share this post

Popular

SpaceX shares new information on Starlink after the successful launch of...

After the successful launch of Elon Musk’s mammoth space mission, Starlink last week, the company has unveiled a brand new website with more details...