Reputation: 211
I am fairly new to Javascript and I was reading the docs and,
According to MDN Docs :-
Keeping an object's internal state private, and generally making a clear division between its public interface and its private internal state, is called encapsulation.
They have not mentioned
How to keep an Object's Internal State Private ?
Also its mentioned further that,
In languages that don't enforce access like this, programmers use naming conventions, such as starting the name with an underscore, to indicate that the property should be considered private.
So what does this line mean
starting the name with an underscore, to indicate that the property should be considered private.
Does this mean if I put _
before a property name it would become private, isn't there a difference between becoming private and making private. Does putting an underscore tells Javascript explicitly that this property is private ?
Also they have not provided any concrete code to explain that part I could only find the pseudocode
class Student : extends Person
properties
year
constructor
Student(name, year)
methods
introduceSelf()
canStudyArchery() { return this.year > 1 }
I googled this and found that closures are used to implement encapsulation behaviour, but the MDN Docs have not stated this anywhere Object-oriented_programming#encapsulation
Question:- How to implement encapsulation in Javascript without closure can we use something like Object.freeze
can someone explain with an example
Thank You.
Upvotes: 3
Views: 217
Reputation: 29281
Does this mean if I put _ before a property name it would become private
No. _
before a field name is used to convey to the reader that these field(s) are meant to be private; technically they are not private. Other code can access them and mutate them.
Fields that are truly private were recently introduced in the Javascript language.
Before the above mentioned feature was introduced, Javascript devs used different techniques to implement private fields - using closures was one of them.
Upvotes: 3