You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript Bank类addBranch方法初始化对象属性报错求助

问题解决:Cannot create property 'customers' on string

错误原因

报错信息TypeError: Cannot create property 'customers' on string 'Branch1'清晰表明:你调用addBranch方法时传入的不是Branch对象实例,而是字符串'Branch1'。字符串属于JavaScript原始类型,无法直接添加自定义属性,因此触发该错误。

解决方案

1. 修正addBranch的调用逻辑

找到报错栈中指向的bank.js:85:6位置(即调用addBranch的代码),确保传入的是Branch类的实例,而非字符串。

错误调用示例:

const bank = new Bank('MyBank');
bank.addBranch('Branch1'); // 错误:传入字符串而非Branch实例

正确调用示例:

// 先定义Branch类(若未定义需补充)
class Branch {
  constructor(name) {
    this.name = name;
  }
}

const bank = new Bank('MyBank');
const branch1 = new Branch('Branch1');
bank.addBranch(branch1); // 正确:传入Branch类实例

2. 给addBranch添加类型校验(推荐)

为避免后续再传入错误类型参数,可在addBranch方法开头增加类型检查,提前抛出明确错误:

addBranch(branch) {
  // 校验参数是否为Branch实例
  if (!(branch instanceof Branch)) {
    throw new Error('addBranch方法必须传入Branch类的实例');
  }
  // 检查分支是否已存在
  if (this.#branches.includes(branch)) return false;

  branch.customers = [];
  this.#branches.push(branch);
  console.log(`Push new branch: ${branch.name}`); // 建议打印分支名称而非整个对象
  return true;
}

3. 更合理的方案:在Branch类内部初始化customers

既然customers是Branch的固有属性,建议直接在Branch类的构造函数中初始化,无需在Bank类中处理:

class Branch {
  #name;
  #customers; // 使用私有属性增强封装性
  constructor(name) {
    this.#name = name;
    this.#customers = []; // 直接初始化客户列表
  }

  // 提供getter方法访问属性
  get name() {
    return this.#name;
  }

  get customers() {
    return [...this.#customers]; // 返回数组副本,避免外部直接修改内部数据
  }
}

此时Bank的addBranch方法只需负责添加Branch实例,无需再处理customers的初始化逻辑。


内容的提问来源于stack exchange,提问作者Kudoo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 02:33:36