In this lesson we will learn about how to define real private properties in javascript classes.
Yonatan Kra: [00:01] I'll define a class Pasta with a constructor that receives a name and stores it in a name variable. In the console, we instantiate a new Pasta and we can access its name property. The problem here is that we can also change the name property.
[00:21] What we'd usually do in such cases is add an _ to the property and add a get to name which returns the _name property. Back in the console, we instantiate a new Pasta and access the name, but we can also access and change the _name. This means that by using _ we count on the developer to not use the private property.
[00:48] This is what the PrivateProperties specification comes to solve. We define a property with a # prefix and use it instead of the _ property. Let's test this in the console. The pasta class is instantiated as expected, and we can access the name. Trying to access the #name we get an error, saying that the private property can only be accessed from inside a class.
[01:20] In summary, we can define private properties in [inaudible] script classes by defining class properties with the # prefix.
Member comments are a way for members to communicate, interact, and ask questions about a lesson.
The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io
Be on-Topic
Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.
Avoid meta-discussion
Code Problems?
Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context
Details and Context
Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!