Private class properties in Javascript

Yonatan Kra
InstructorYonatan Kra
Share this video with your friends

Social Share Links

Send Tweet

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.