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

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

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