3

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.

2
  • The article you linked is explaining encapsulation in OOP in general. They explain how to implement encapsulation using JavaScript in the next chapter. Commented Aug 31, 2022 at 11:23
  • I’m voting to close this question because OP cannot find the required information from a linked documentation, because the information is in the next chapter of the linked documentation. Commented Aug 31, 2022 at 11:25

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.