Reputation:
This is a common idiom encapsualted into a function by undescore.
_.each(obj1, function(val, key, context, obj2){
});
What is the purpose of the 4th argument in the callback - obj2
. This is the object one is looping through so it should always be available in the outer scope as obj1
.
Is there an example of where you would need access to obj1
through obj2
.
I'm trying to understand what obj2
is for. Here is the exact line of code - line 83.
if (iterator.call(context, obj[i], i, obj) === breaker) return;
Upvotes: 0
Views: 42
Reputation: 1074674
What is the purpose of the 4th argument in the callback -
obj2
. This is the object one is looping through so it should always be available in the outer scope asobj1
.
It's so you can reuse the same function for looping through multiple objects, and still have access to the object being iterated within the function. The function you use might well be define elsewhere. You could have a library of functions you use for various iteration purposes. It's rare to want to know what the object is (hence it being so far into the argument list), but there are use cases.
Upvotes: 1
Reputation: 281605
If you were passing a reference to a named function as the callback, obj1
might not be available:
function my_callback(val, key, context, obj2) {
...
}
function do_stuff() {
var obj1 = ...
_.each(obj1, my_callback);
}
Upvotes: 4