【问题标题】:How to access methods through from another class and create object如何从另一个类访问方法并创建对象
【发布时间】:2021-11-16 23:17:23
【问题描述】:

OOP Javascript 新手!我有 2 个课程,订单和客户。我有一个方法 getName()。我希望客户作为我在 Order 类中的属性之一。我已经为两者创建了对象,但似乎无法访问订单对象中的客户名称。

Customer.js

class Customer{
constructor(id, name, address,creditCard) {
this._id=id;
this._name=name;
this._address=address;
this._creditCard=creditCard;
}

getName(){
    return this._name;
}
}

Order.js

class Order {
customer;
constructor(id, date) {
  this._id = id;
 this._date=date;

this.customer=new Customer();
}

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

data.js

  const customer1 = new Customer(123,"John","123 E Cookie St",'xxxx xxxx xxxx 1223');

   const order1= new Order(801,'January 12, 2021 01:15:00',customer1.getNameCustomer() );

  let orders=[order1];

【问题讨论】:

  • 您正在调用不存在的 customer1 上的 getNameCustomer 方法。你应该使用customer1.getName()...
  • 如果不传递Customer 所需的数据,这将毫无意义this.customer = new Customer();

标签: javascript class oop


【解决方案1】:

您正在调用不存在的 customer1 上的 getNameCustomer 方法。你应该使用

customer1.getName()

但如果你在Order 类中传递customer 对象并将其作为属性,你可以做得更好:

class Customer {
  constructor(id, name, address, creditCard) {
    this._id = id;
    this._name = name;
    this._address = address;
    this._creditCard = creditCard;
  }

  getName() { return this._name; }
}

class Order {
  constructor(id, date, customer) {
    this._id = id;
    this._date = date;
    this._customer = customer;
  }

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

const customer1 = new Customer(123, "John", "123 E Cookie St", "xxxx xxxx xxxx 1223");

const order1 = new Order(801, "January 12, 2021 01:15:00", customer1);

console.log(order1);
console.log(order1.getNameCustomer());
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

  • 非常感谢您帮助我理解!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-23
相关资源
最近更新 更多