I have a JavaScript class Bank with a method "addBranch" that adds a Branch object to an array of branches. I want to initialize a custom attribute "customers" for each Branch object when it is added to the array.
Here is a simplified version of the code:
class Bank {
#name
#branches
constructor(name) {
this.#name = name
this.#branches = []
}
// name getter
get name() {
return this.#name
}
// branches getter
get branches() {
return this.#branches
}
// adding branch method
addBranch(branch) {
// check if branch is already existed
if (this.#branches.includes(branch)) return false
// Initialize customers attribute for the new branch
branch.customers = []
this.#branches.push(branch)
console.log(`Push new branch: ${branch}`)
return true
}
I have tried to use "branch.customers = []" but it doesn’t work for me
TypeError: Cannot create property ‘customers’ on string ‘Branch1’
at Bank.addBranch (C:UsersnpdkhDesktopIntegrifyfs17-week2-TSsrcbank.js:25:22)
at Object. (C:UsersnpdkhDesktopIntegrifyfs17-week2-TSsrcbank.js:85:6)
at Module._compile (node:internal/modules/cjs/loader:1256:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
at Module.load (node:internal/modules/cjs/loader:1119:32)
at Module._load (node:internal/modules/cjs/loader:960:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:23:47
Node.js v18.17.1
2
Answers
const myBranch = new Branch(‘Main Branch’);
const myBank = new Bank(‘My Bank’);
myBank.addBranch(myBranch);
console.log(myBranch.customers); // outputs :[]
The OP might think about implementing an abstraction for
Branch
as well, maybe even forCustomer
. But one does not necessarily need to go that path. It is all about at which point one wants to manage all of the involved object states. Depending on that one could also go with an approach that just passes simple object types with unprotected properties around.Going with another abstraction will also free the OP from the original task, which was adding a
customers
property to the passed branch value/object.In addition one needs to rethink of how one wants to check the sameness of to be added branch and customer items/objects. The next provided example code does implement a checking exclusively on such items’
name
properties which might be a weak sameness comparison, but one could extend this comparison approach as needed.