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

JavaScript OOP 如何在Order类中访问Customer类的方法获取客户名

问题原因

  • Order类的构造函数没有设计接收外部Customer实例的参数,反而在内部实例化了无参数的空Customer对象,该对象的_name属性为undefined,调用getName()自然无法返回正确值
  • 实例化Order时传入的第三个参数错误:getNameCustomer()是Order类的方法,Customer类没有该方法,你应该直接传入已经创建完成的customer1实例

修正代码

Order.js

class Order {
  customer;
  // 构造函数新增customer参数
  constructor(id, date, customer) {
    this._id = id;
    this._date = date;
    // 直接绑定外部传入的customer实例,删除内部新建Customer的逻辑
    this.customer = customer;
  }

  getNameCustomer() {
    return this.customer.getName();
  }
}

data.js

const customer1 = new Customer(123,"John","123 E Cookie St",'xxxx xxxx xxxx 1223');
// 第三个参数直接传入customer1实例
const order1= new Order(801,'January 12, 2021 01:15:00',customer1);

let orders=[order1];

// 测试调用可以正常输出客户名 John
console.log(order1.getNameCustomer())

Customer.js原有逻辑无需修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 10:06:04