Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

182
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda