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

130
Vistas
print foo by modifying the below piece of code

Without hardcoding the string, 'foo', how can i modify the code above so that it prints out 'foo 1', 'foo 2', and 'foo 3' each on separate lines.

const obj = {
  x: 'foo',
  f: function() {
    [1, 2, 3].forEach(function(num) {
      console.log(this.x, num);
    });
  }
}

obj.f();

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Classic "function" declarations will bind to the caller's "this" environment instead of how most languages do it. Traditionally, this can be fixed with the bind method on a function as follows:

const obj = {
     x: 'foo',
      f: function() {
          [1, 2, 3].forEach(function(num) {
              console.log(this.x, num);
          }.bind(this))
        }
    };

The simpler approach is to just use the new arrow syntax, which will bind the function as you would naturally expect.

This line:

[1, 2, 3].forEach(function(num) {

To this:

[1, 2, 3].forEach((num)=> {
about 4 years ago · Juan Pablo Isaza Denunciar

0

const obj = {
  x: 'foo',
  f: function() {
    [1, 2, 3].forEach(function(num) {
      console.log(`${obj.x} ${num}`);
    });
  }
}

obj.f();
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