Reputation: 28284
In the codebase that I am trying to figure out, I see that a js file (myloopfile.js) being imported into another js file. I am trying to make sense of some of the code used there
this is myloopfile.js
function method1(value) {
// return something
}
var myLooper = function (obj, iterator, context) {
var key;
if (obj) {
if (typeof obj === 'function') {
for (key in obj) {
if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
iterator.call(context, obj[key], key);
}
}
} else if (obj.forEach && obj.forEach !== forEach) {
obj.forEach(iterator, context);
} else if (isArrayLike(obj)) {
for (key = 0; key < obj.length; key++)
iterator.call(context, obj[key], key);
} else {
for (key in obj) {
if (obj.hasOwnProperty(key)) {
iterator.call(context, obj[key], key);
}
}
}
}
return obj;
};
……………………………………………………………………………….
the myLoop in myloopfile.js is called like this
var looper = require(‘../myloopfile.js);
looper({
loop1: function(Home) { //do something },
loop2: function(Home) { //dosomething }
}, function(return1, return2) {
//do something else
});
I am trying to find out where this
function(return1, return2) {
//do something else
});
coming from ? I don’t see anything in that file that suggests that there is a method attached to it. Also where are the parameters return1 and return2 coming from? is this some javascript way to attach things ?
Upvotes: 0
Views: 31
Reputation: 6211
var myLooper = function (obj, iterator, context) {
/* .... */
iterator.call(context, obj[key], key);
/* .... */
};
You pass:
looper({
loop1: function(Home) { //do something },
loop2: function(Home) { //dosomething }
}, function(return1, return2) {
//do something else
});
So
obj = {
loop1: function(Home) { //do something },
loop2: function(Home) { //dosomething }
}
and
iterator = function(return1, return2) {
//do something else
}
The Function.prototype.call()
method calls a function with a given this
value and arguments provided individually. Therefore, inside you iterator function:
this = context;
return1 = obj[key];
return2 = key;
Upvotes: 1
Reputation: 2686
So javascript has function that are called anonymous function
that don't need a function name.
Basically it is used (in this instance) as a way to be an expantion of a parameter.
Take for example the javascript function setTimeout
Well setTimeout
can take an anonymous function as one of its parameters i.e
var timer = setTimeout(function{
//do something
},
2000);
// setTimeout(function, time, paramters)
So you don't have to declare a function and pass it in as a parameter
Back to your case, you have this anonymous function that takes return1 and return2
So in the end:
return1 = obj[key];
return2 = key;
Upvotes: 1