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

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

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 Relatório

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