Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

368
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!