|
| 1 | +# Private Fields and Defaults |
| 2 | + |
| 3 | +👨💼 Classes can hide implementation details using private fields and provide |
| 4 | +flexibility with default parameter values. |
| 5 | + |
| 6 | +## Private Fields |
| 7 | + |
| 8 | +JavaScript has native private fields using the `#` prefix. These fields are |
| 9 | +truly private—they can only be accessed inside the class: |
| 10 | + |
| 11 | +```ts |
| 12 | +class BankAccount { |
| 13 | + #balance: number = 0 // Truly private - not accessible outside the class |
| 14 | + |
| 15 | + deposit(amount: number) { |
| 16 | + this.#balance += amount |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +const account = new BankAccount() |
| 21 | +account.#balance // ❌ Error! Private field not accessible |
| 22 | +``` |
| 23 | + |
| 24 | +Private fields enable **encapsulation**—hiding internal implementation details |
| 25 | +from code outside the class. This prevents accidental modification and makes |
| 26 | +your code more maintainable. |
| 27 | + |
| 28 | +## Default Parameter Values |
| 29 | + |
| 30 | +Constructors can use default parameter values to make some parameters optional: |
| 31 | + |
| 32 | +```ts |
| 33 | +class User { |
| 34 | + name: string |
| 35 | + role: string |
| 36 | + |
| 37 | + constructor(name: string, role: string = 'user') { |
| 38 | + this.name = name |
| 39 | + this.role = role |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +const user = new User('Alice') // role defaults to 'user' |
| 44 | +const admin = new User('Bob', 'admin') // role explicitly set |
| 45 | +``` |
| 46 | + |
| 47 | +🐨 Open <InlineFile file="index.ts" /> and: |
| 48 | + |
| 49 | +1. Use `#` prefix to create private fields |
| 50 | +2. Use default parameter values in constructors |
| 51 | +3. Create classes that encapsulate their internal state |
| 52 | + |
| 53 | +💰 Use `#` to declare a private field—it's truly private, not just a convention. |
| 54 | + |
| 55 | +💰 Default parameters let you create flexible constructors with sensible defaults. |
| 56 | + |
| 57 | +📜 [MDN - Private class features](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields) |
0 commit comments