- Anonymous function and direct calling
call()
can be used to invoke anonymous function directly after stating it.
-
(function() {...}).call(thisArg)
- For each items in an object array
-
for (let i = 0; i < arr.length; i++) {
(function() {...}).call(arr[i])
};
- Don't forget keyword
this
- Task
- Create anonymous function for printing content of each properties in an object array, with index numbering but starting from 1.
- Basic way
-
const animals = [
{species: "Dodo", name: "Dottie"},
{species: "Flummel", name: "Op"},
{species: "Flummel", name: "Ed"}
];
for (let i = 0; i < animals.length; i++) {
console.log(`#${i+1} ${animals[i].species}: ${animals[i].name}`);
};
- Using function
-
const animals = [
{species: "Dodo", name: "Dottie"},
{species: "Flummel", name: "Op"},
{species: "Flummel", name: "Ed"}
];
function print(arr, i) {
console.log(`#${i+1} ${arr[i].species}: ${arr[i].name}`);
}
for (let i = 0; i < animals.length; i++) {
print(animals, i)
};
- Using anonymous function and direct
call()
- Working from the
print
function above
-
- The
this
is animals[i]
- Then the call:
call(animals[i], i)
- And inside the function:
this.species
and this.name
- Parameters
arr
and i
are not necessary
- From this:
-
const animals = [
{species: "Dodo", name: "Dottie"},
{species: "Flummel", name: "Op"},
{species: "Flummel", name: "Ed"}
];
for (let i = 0; i < animals.length; i++) {
(function (arr, i) {
console.log(`#${i+1} ${arr[i].species}: ${arr[i].name}`);
}).call(animals[i], animals, i)
};
- To this:
-
const animals = [
{species: "Dodo", name: "Dottie"},
{species: "Flummel", name: "Op"},
{species: "Flummel", name: "Ed"}
];
for (let i = 0; i < animals.length; i++) {
(function () {
console.log(`#${i+1} ${this.species}: ${this.name}`);
}).call(animals[i])
};