Private Fields in Classes
Private fields in JavaScript classes give you a way to hide data from outside code, reinforcing the principle of encapsulation. When you use the # symbol before a field name in a class, you create a private field. This means the field is only accessible within the class body itself—code outside the class cannot read or write to it directly. By restricting access to sensitive data, you prevent accidental modification and help keep your objects' internal state safe. This is especially important in situations where exposing data could lead to bugs or security issues.
123456789101112131415161718192021222324252627282930class BankAccount { #balance; // private field constructor(initialBalance) { this.#balance = initialBalance; } deposit(amount) { if (amount > 0) { this.#balance += amount; } } withdraw(amount) { if (amount > 0 && amount <= this.#balance) { this.#balance -= amount; return amount; } return 0; } getBalance() { return this.#balance; } } const account = new BankAccount(100); account.deposit(50); console.log(account.getBalance()); // 150 console.log(account.#balance); // SyntaxError: Private field '#balance' must be declared in an enclosing class
Merci pour vos commentaires !
Demandez à l'IA
Demandez à l'IA
Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion
Awesome!
Completion rate improved to 6.25
Private Fields in Classes
Glissez pour afficher le menu
Private fields in JavaScript classes give you a way to hide data from outside code, reinforcing the principle of encapsulation. When you use the # symbol before a field name in a class, you create a private field. This means the field is only accessible within the class body itself—code outside the class cannot read or write to it directly. By restricting access to sensitive data, you prevent accidental modification and help keep your objects' internal state safe. This is especially important in situations where exposing data could lead to bugs or security issues.
123456789101112131415161718192021222324252627282930class BankAccount { #balance; // private field constructor(initialBalance) { this.#balance = initialBalance; } deposit(amount) { if (amount > 0) { this.#balance += amount; } } withdraw(amount) { if (amount > 0 && amount <= this.#balance) { this.#balance -= amount; return amount; } return 0; } getBalance() { return this.#balance; } } const account = new BankAccount(100); account.deposit(50); console.log(account.getBalance()); // 150 console.log(account.#balance); // SyntaxError: Private field '#balance' must be declared in an enclosing class
Merci pour vos commentaires !