OOP Encapsulation in JavaScript | private & public | code practice | factory function #kody_az
Dərs haqqında
JavaScript-də inkapsulyasiya (encapsulation) obyektin daxili məlumatını gizlətmək və çölə yalnız nəzarətli “API” (metodlar/properties) vermək deməkdir.
Çox yayılmış bir konvensiya var: daxili sahələri _balance kimi underscore _ ilə yazırlar və bunun mənası “buna toxunma”dır, amma bu əsl private deyil.
Yəni istəsən çöldən yenə də _balance-u oxuya və dəyişə bilərsən, sadəcə bu etik deyil.
Həqiqi (real) gizlilik üçün modern JS-də hash # istifadə olunur: #password kimi sahələr tam private sayılır.
#private sahəyə sinifin (class) çölündən toxunmağa çalışsan, JS bunu SyntaxError kimi bloklayır.
Eyni qayda private metodlar üçün də keçərlidir: #helper() kimi metodlar yalnız class-in içində işlədilir.
Inkapsulyasiya praktikada belə görünür: sən #password kimi daxili dəyəri çölə vermirsən, onun yerinə “yoxla”, “dəyiş”, “balansı artır” kimi public metodlar verirsən.
Beləliklə obyekt öz qaydalarını qoruyur və yanlış dəyər (məsələn mənfi balans, səhv format) içəri düşmür.
Private property elan etmək üçün onu class daxilində # ilə yazırsan və ya constructor-da this.#field = ... şəklində təyin edirsən.
Qısası, _ — sadəcə “toxunma” mesajıdır, # isə dilin özü tərəfindən qorunan əsl gizlilikdir.
=====
In JavaScript, encapsulation is often done by keeping data “private” and letting outside code interact only through a public API.
A common convention is naming internal fields with an underscore like _balance, which signals “don’t touch this directly,” but it is not truly private.
For real privacy in modern JS classes, you declare private fields with a hash prefix like #password, and those fields are accessible only inside the class body.
If you try to read or write a #privateField from outside the class, you get a SyntaxError, because the language blocks it at parse time.
You can also make private methods using the same # syntax, which helps hide helper logic that should not be called from outside.
Encapsulation usually means you expose public methods (for example, “checkPassword” or “deposit”) that safely work with private fields instead of exposing the fields themselves.
A typical pattern is to keep the actual value private and provide a controlled way to read it, like a getter, or to validate changes through methods.
To declare private properties, you define them inside the class with # (either with an initial value or assigned in the constructor).
This approach protects your object’s internal state, so other code can’t accidentally break its rules by modifying internals directly.
So, underscore is “public but please don’t,” while # is “actually private by the language.”
#kody_az #kodyaz #js #javascript #nodejs #es6 #viral #viralcode #nodejs #viralvideo #random #code #coder #azerbaycan #azerbaijan #baku #baki #programming #programmer #codes #hazırlıq #hazirliq #kurs #kurslar #course #courses #online #onlinecourses #test #quiz #oop