Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

186
Views
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];
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!