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

374
Visualizações
Javascript call() on anonymous function

I'm trying to understand one of the examples on MDN for Function.prototype.call(), "Using call() to invoke an anonymous function":

const animals = [
  { species: 'Lion', name: 'King' },
  { species: 'Whale', name: 'Fail' }
];

for (let i = 0; i < animals.length; i++) {
  (function(i) {
    this.print = function() {
      console.log('#' + i + ' ' + this.species
                  + ': ' + this.name);
    }
    this.print();
  }).call(animals[i], i);
}

Is the i at line #7 (function(i) { a repetition/optional?

It seemed to me that }).call(animals[i], i); at line #12 with the second parameter is already passing i, so to make my test, I wanted to remove it

I mean that at line #7, instead of (function(i) { I have tried (function() { and as I was supposing, it gives the same result.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Thank too Jonsharpe I clarified myself the mechanism

Since this was a didactic question , I share the explicitation to students like me

first of all, the code is misleading, so to better understand it, as suggested by Jonsharpe it is better to replace 'i' with 'index'

const animals = [
    { species: 'Lion', name: 'King' },
    { species: 'Whale', name: 'Fail' }
  ];
  
  for (let i = 0; i < animals.length; i++) {
    (function(index) {
      this.print = function() {
        console.log('#' + index + ' ' + this.species + ': ' + this.name);
      }
      this.print();
    }).call(animals[i], i);
  }

how should it be read, with a paraphrase it does mean

.call the function(index) passing it (animals[i], i) as parameters

the first parameter, an object, is then available through this. the second is passed through index

At line #8 is added and defined a method 'print' to the object

At line #11 this new method is run/called this.print();

The process is repeated animals.length times

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