Private class properties in Javascript

Yonatan Kra
InstructorYonatan Kra
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 4 years ago

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.

egghead
egghead
~ a minute ago

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

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

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!

Markdown supported.
Become a member to join the discussionEnroll Today