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

348
Visualizações
JavaScript: How to push to an array inside an object that was created inside an arrow function

So how do I push to the CONSUPTION array? Using THIS is not working and ia have no clue on how to make the ORDER work.

const createMenu = (menu) => ({
        fetchMenu: () => menu,
        consumption: [1,2],
        order: (string) => {
          this.consumption.push(string);
        },
        pay: () => {
          let cont = 0
          const cardapio = { ...menu.food, ...menu.drink}
          for (let itens of this.consumption){
            cont += cardapio[itens];
          };
          return cont;
        },
      });
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Change the order arrow function to a regular function, it's not a good idea to use it in an object.

The reason for that is because that In regular functions the this keyword represented the object that called the function. Unlike regular functions, arrow functions do not have their own this. The value of this inside an arrow function remains the same throughout the lifecycle of the function and is always bound to the value of this in the closest non-arrow parent function.

const createMenu = (menu) => ({
        fetchMenu: function(){ return menu},
        consumption: [1,2],
        order: function(string)  {
          this.consumption.push(string);
        },
        pay: function() {
          let cont = 0
          const cardapio = { ...menu.food, ...menu.drink}
          for (let itens of this.consumption){
            cont += cardapio[itens];
          };
          return cont;
        },
      });
      
      const menu = createMenu();
      console.log(menu.consumption);
      menu.order(3);
      console.log(menu.consumption);

More about this in arrow function could be found here

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