Privacy and Static Members
Introduction: Protecting Your Data
In our first lesson, we learned how to create blueprints for objects using the class keyword. We used the constructor to set initial properties, like a person's name or a book's title. While that approach is a great start, it has a small problem: any part of your program can reach inside your object and change that data. For example, if you have a bank account object with a balance, you probably do not want someone to accidentally set that balance to a negative number or a piece of text.
In professional software development, we use a concept called encapsulation. This means we bundle the data and the methods that work on that data together, but we also hide the "innards" of the object from the outside world. By the end of this lesson, you will know how to use private fields to hide sensitive data, and how to use getters and setters to provide a safe way for others to interact with that data.
Private Instance Fields With
Up until recently, JavaScript did not have a way to truly hide data inside a class. Developers often used a naming convention, like putting an underscore before a variable name (such as _balance), to tell others, "Please do not touch this." However, this was just a suggestion and did not actually stop anyone from changing the value.
Modern JavaScript now includes private fields. To make a property private, you must declare it at the top of your class using the # symbol before its name. Once a property is marked with a #, it can only be accessed or changed inside the code of that specific class. If you try to access it from outside the class, JavaScript will throw a SyntaxError.
In the code above, the #balance field is declared before the constructor. This tells the JavaScript engine that this piece of data is "private" to the Account class. When we create an instance called myAccount, the balance is safely tucked away. Because the language itself enforces this rule, it is impossible for another developer to accidentally overwrite the balance from outside the class definition.
Getters: Controlled Read Access
