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

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

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