Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

185
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda