Thanks for posting this! While I mostly recommend against OOP in JavaScript, I think it's an important paradigm to understand.
I think your Abstraction section isn't ideal. The way you define _balance and the related methods inside the constructor mixes actual OOP with closures. The getBalance and deposit methods are not members of the class this way, they are redefined for each instance.
This was how we managed private values prior to ES2022 when Private elements were added to the spec.
Using the private elements simplifies the design makes use of class-level methods.
// Abstraction example with a BankAccount classclassBankAccount{// Private variable to hold the balance// It cannot be accessed directly outside the class#balanceconstructor(owner,balance){this.owner=owner;// account owner's namethis.#balance=balance;}// Method to check current balance (controlled access)getBalance(){returnthis.#balance;}// Method to deposit money (changes balance internally)deposit(amount){this.#balance+=amount;console.log(`Deposited ${amount}. New balance: ${this.#balance}`);}}// Create a new bank account with an initial balance of 1000constaccount=newBankAccount("Peace",1000);// Deposit money using the provided methodaccount.deposit(500);// Output: Deposited 500. New balance: 1500// Access the balance safely through the methodconsole.log(account.getBalance());// Output: 1500// Direct access like account.#balance is not possible (hidden!)
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Thanks for posting this! While I mostly recommend against OOP in JavaScript, I think it's an important paradigm to understand.
I think your Abstraction section isn't ideal. The way you define
_balanceand the related methods inside theconstructormixes actual OOP with closures. ThegetBalanceanddepositmethods are not members of the class this way, they are redefined for each instance.This was how we managed private values prior to ES2022 when Private elements were added to the spec.
Using the private elements simplifies the design makes use of class-level methods.