JavaScript private class fields and methods are new features for JavaScript classes. In this tutorial, you will learn all you need to know about this feature. You will learn about what private methods and class fields are and how they work. You will also learn how to use them in your projects.

Introduction

When you want to add some data to JavaScript class you can do so through class properties. These properties are by default always public. This also means that they are publicly accessible and modifiable. The same also applies to class methods. They are also public by default.

This might often be okay. However, sometimes, you may want to keep some properties or methods private. You may want to make them inaccessible from the outside of the class they are defined in. This is where private methods and class fields can be handy.

Keeping it private

The idea of keeping some things private is simple and straightforward. When you want to keep something private, be it a property or method, it should be accessible only from one place. This place is the class in which you defined that property or method.

If you try to access private class field or method from elsewhere JavaScript should not allow it. This includes outside the class in which the class field or method is defined. Also any instance of that class. However, it is possible to access private class field from a method inside the same class.

#javascript #javascript classes #javascript private class

Private Class Fields and Methods in JavaScript Classes
1.25 GEEK