Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Private class properties in Javascript


    In this lesson we will learn about how to define real private properties in javascript classes.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Yonatan Kra: 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.

    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.

    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.

    In summary, we can define private properties in inaudible script classes by defining class properties with the # prefix.