Explain Codes LogoExplain Codes Logo

Private properties in JavaScript ES6 classes

javascript
private-properties
es6-classes
javascript-features
Anton ShumikhinbyAnton Shumikhin·Nov 9, 2024
TLDR

Declare private properties in ES6 classes using a # prefix. These are limited to the class's methods, providing enhanced encapsulation.

class MyClass { #privateProperty; // As private as your incognito browser tab ;) constructor(value) { this.#privateProperty = value; } // A public method to peep into our private life getPrivate() { return this.#privateProperty; } } const obj = new MyClass("incognito"); console.log(obj.getPrivate()); // "incognito"

Directly accessing a #privateProperty is like trying to open a locked door—it throws a SyntaxError:

console.log(obj.#privateProperty); // SyntaxError: Like trying to spy without a telescope!

Before ES2022 introduced genuine private fields, developers often used an underscore _ to indicate a limited privacy, known as convention-based privacy.

Easy access: Best Practices & Common Patterns

How to achieve 'real' privacy

From ES2022 onwards, JavaScript supports native private fields. Unlike a diary with a lock, these can't be picked open—they ensure real privacy:

  • Private fields are not enumerable: They don't show up in a property listing.
    console.log(Object.keys(obj)); // [ 'getPrivate' ] console.log(Reflect.ownKeys(obj)); // [ 'getPrivate' ]
  • The # screams no trespassing—private fields are not accessible with APIs like Object.getOwnPropertySymbols.

Making up for the 'missing' in previous JavaScript versions

Before JS blessed us with native private fields in ES2022, developers used some tricks to simulate privacy:

  • Symbols: Symbols make properties hard to accidentally access. You need the exact symbol to get to the property—like a VIP pass!
  • Scoped WeakMaps: This involves creating a kind of VIP lounge for each private property, which avoids overtaxing the bouncers (methods).
  • Closures: Imagine slipping a secret note in a bottle and tossing it into the ocean. That's kind of how data hides in closures.

Data security and encapsulation

Steer clear of directly attaching sensitive data to objects. Instead:

  • Manage private data access with getters/setters, like having a butler to do your bidding.
  • Redefine getters/setters per instance—because your data is valuable, and you're the king!

Browser compatibility: Friends or foes?

Double-check compatibility before using latest features like ES2022 private properties. Tools like Babel can help you future-proof your code.

Adding a moat around your castle: private methods

You can also secure methods using the # (hashtag of privacy!) prefix in classes:

class MyClass { #privateMethod() { ... }// The method that's playing hard to get publicMethod() { this.#privateMethod(); // Private, but callable inside the class (Like VIP access!) } }

Advanced Insights and Practical Tips

Applying private properties: why you should care

Utilizing private properties in JavaScript is akin to having a home security system.

  • Better sovereignty by denying unlawful access from external operations.
  • Achieve tighter encapsulation - the whole point of OOP.
  • Increase maintainability, by masking the properties that are not meant for outside interaction.

Code management and effective use

For maintainable, legible, and bare-bones effective code:

  • Use meaningful names to define the purpose of each property (be it private or public).
  • Don't overdo the use of symbols (Symbols are good, but then, so is cheesecake, in moderation!).
  • Design your modules such that the public APIs are exposed via export, and everything else remains for internal use. Kind of like a house with a public address, but a private interior.

Common traps and precautions

Watch out for potential slip-ups:

  • Don't presume private properties to behave like their public counterparts.
  • In closures, private data can sometimes act like a quill in a haystack
  • Be careful with WeakMaps—if seized globally, they can spill secrets.