我有一个 JavaScript 类 Bank,其方法为“addBranch”,该方法将 Branch 对象添加到分支数组中。我想在将每个 Branch 对象添加到数组时初始化一个自定义属性“customers”。
这是代码的简化版本:
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
}
我尝试使用“branch.customers = []”,但它对我不起作用
TypeError:无法在字符串“Branch1”上创建属性“customers” 在 Bank.addBranch (C:\Users pdkh\桌面\Integrify s17-week2-TS\src ank.js:25:22) 在对象。 (C:\用户 pdkh\桌面\Integrify s17-week2-TS\src ank.js:85:6) 在Module._compile(节点:内部/模块/cjs/loader:1256:14) 在 Module._extensions..js (节点:内部/模块/cjs/loader:1310:10) 在Module.load(节点:内部/模块/cjs/loader:1119:32) 在 Module._load (节点:内部/模块/cjs/loader:960:12) 在 Function.executeUserEntryPoint [作为 runMain] (节点:internal/modules/run_main:81:12) 在节点:内部/主/run_main_module:23:47
Node.js v18.17.1
const myBranch = new Branch('主分支'); const myBank = new Bank('我的银行');
myBank.addBranch(myBranch); console.log(myBranch.customers); // 输出 :[]