Information Hiding
Let's reiterate that, at the time of writing, JavaScript class syntax does not allow for declaring fields. It is, however, planned for the future to allow field declaration using a syntax like this:
class Account {
balance = 0;
deposit(amount) {
this.balance += amount
}
}
There are applications (called transpiler), like Babel that allow you to write your source code using proposed syntaxes (such as the one above). You can then transpile your source code to the standard JavaScript.
There is no notion of visibility modifier in JavaScript class syntax. So, for example, you cannot make a property (attribute/method) private. However, there are ways to mimic this behavior, which typically involves clever function closure.
class Account { constructor(balance){ this.getBalance = function() { return balance } this.deposit = function (amount) { balance += amount } } } const checking = new Account(100); checking.deposit(20); console.log(checking.getBalance()); console.log(checking.balance);
There is also a proposal to declare private fields as follows:
class BankAccount {
#balance = 0;
deposit(amount) {
this.#balance += amount
}
}
Moreover, some programmers employ various conventions to "signal" a property is private. For example, inspired by Python programmers, some adopted the convention of prefixing a private property name with an underscore.
class BankAccount {
constructor(balance){
this._balance = balance;
}
deposit(amount) {
this._balance += amount
}
}
Prefixing the property name with an underscore does not protect the property in any way; it merely signals to the outside: "You don't need to know about this property."