The author uses the term encapsulation a lot, yet when talking about encapsulation and providing example code the author fails almost with every single example code. In addition the author uses the term encapsulation where subject/context and example code clearly show grouped but public properties whereas the goal of encapsulation is data protection.
My conclusion. The author, if at all, only possesses superficial knowledge if it comes to the foundation/basics of OOP. Worse, the author likewise lacks any deeper knowledge of the JavaScript language's core features.
At the author. Please don't rely on the help of a generative AI, when you are not a pro yourself in the field you're writing about, especially when the topic is JavaScript where the output of deep learning models definitely will not all of a sudden be smarter/wiser than all the false and low quality content of the web that was ever written about JavaScript. No wonder the article repeats a lot of false narratives about OO principles in general and OO in JavaScript specifically and comes with badly designed/generated code examples.
Some more detailed critique.
Until the get/set related ClassName
example, none of the example codes shows/implements/works with encapsulated data. Everything until that example exclusively features public properties.
Now to the bad design of the author’s following example code …
class ClassName {
constructor(property) {
this._property = property;
}
// Getter
get property() {
return this._property;
}
// Setter
set property(value) {
this._property = value;
}
}
The get/set syntax immediately gets rendered obsolete since both getter and setter read from, respectively write to a public property. Its pseudo private underscore annotation does not make it private, period.
A correct example code of cause has to make use of real encapsulated data, and since it all is about classes, one has to use a private property …
class ClassName {
#property;
constructor(property) {
this.#property = property;
}
// Getter
get property() {
return this.#property;
}
// Setter
set property(value) {
this.#property = value;
}
}
The chapter which follows after the author’s pointless example code is called ”Example: Using Getters and Setters in JavaScript Classes for Encapsulation”, but gets everything wrong again. The author or the GAI even dares to state in one of the bulletpoints …
— We define a
User
class with private properties_username
and_age
.
No, we do not. The author again mistakes an annotation for real privacy.
I’m not going to correct the class User { ... }
example code here. A correctly implemented version has to follow the example of the above corrected class ClassName { ... }
.