In this blog, we will look into public and private instance class fields in detail.
Public instance fields
Public class fields allow us to add instance properties to the class definition with the assignment operator (=).
Consider a simple React component of incrementing the count.
In this example, we define instance fields and bind methods in the constructor. We can make the code a little more intuitive by using the new class syntax.
The new public class fields syntax allows us to add instance properties directly as a property on the class without having to use the constructor method. This simplifies the class definition making the code look pretty readable with less boilerplate!
Now, a lot of people reading this are probably thinking
which is true.
it is not standard ECMAScript
and isn’t enabled by default.
If the project is created using
it is enabled by default or else we have to include the right
Babel 7.14 enables class fields & private methods by default
Let’s check out more about public instance fields.
- Public instance fields exist on every created instance of a class.
They are added with
Object.defineProperty()either at construction time in the base class (before the constructor body runs) or just after
super()returns in a subclass.
- Fields, which are not initialized are set to
- Like properties, field names may be computed.
Private instance fields
Private fields are accessible on the class constructor from inside the class declaration itself. When we want to prevent people from accessing the property directly private class fields should be used.
Private fields are based on syntax using a
both when declaring a field and when accessing it.
Check out more details about the private instance fields in our previous blog.
See the private syntax FAQ for discussion of alternatives considered and the constraints that led to this syntax.