tmxgold
tmxgold

Reputation: 1

How to access methods through from another class and create object

New to OOP Javascript! I have 2 classes, Order and Customer. I have a method getName(). I want customer as one of my properties in the Order class. I have created objects for both but can't seem to access the customer name in the order object.

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];

Upvotes: 0

Views: 664

Answers (1)

DecPK
DecPK

Reputation: 25398

You are calling getNameCustomer method on customer1 which doesn't exist. You should use

customer1.getName()

But you can do better if you pass the customer object in the Order class and make it a property as:

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; }

Upvotes: 1

Related Questions