TECH TALKS

Private variables (fields), private methods, private accessors. Javascript finally gave “some privacy” to classes

author
Nikola Tasikj
23 Jul,2020

Private fields are supported by Google Chrome v74+ and NodeJs 12+
Private methods and accessors are supported by Google Chrome v84+

Day by day, we are all witnessing the rapid progress of Javascript. There are still some mind blowing things that your non-javascript colleagues will joke about, but days without having private fields in classes are far behind us.

In March last year, V8 (Google’s Javascript engine) was upgraded with private fields in classes. From that moment we are stepping forward in respecting Encapsulation. Defining classes with private fields is done by prepending it with a # prefix. This syntax was part of global criticism because other languages are using private for the same thing and it looks like a hack, but for now, there is no info that this will be changed in the future.

Credits

Private variables (fields)

Defining private fields in class (and using them in object — instance for that class) means accessing that field will be allowed only to the current object (inside that same class). Setting value for that variable or getting it needs to be done by setter and getter. I guess that this old part is already routine for you, but let me show you one simple example of how private fields work in javascript. If you want to create a class with private fields, you should use:

class Person {
    #name
    #age
}

In this class as you can see I prepend # on those 2 variables. This will create 2 variables: name and age that will be private. If you try to create an object from this class and then access any of these two variables it will throw an error.

Keep in mind that # is part of that private variable and the way how javascript recognizes private fields at the same time. Setting a name