I'm trying to understand underscore's invoke()
function, but I'm having trouble in a few areas. Here's the code from the annotated source:
_.invoke = function(obj, method) {
var args = slice.call(arguments, 2);
var isFunc = _.isFunction(method);
return _.map(obj, function(value) {
var func = isFunc ? method : value[method];
return func == null ? func : func.apply(value, args);
});
};
In this example:
_.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
=> [[1, 5, 7], [1, 2, 3]]
I understand what is going on; however, in the source code, I don't understand the function of args
. In what kind of situations would additional arguments need to be used?
I'm also new to programming, and I'm struggling with how apply
is being used here. I'm guessing it's because I don't fully understand the use of invoke
, namely the use of args
. Still, in looking at examples provided in Mozilla's documentation, one example used Math.max.apply(*null*, numbers)
, so why is it being applied to value
in the source code?
Note: I've read many articles on it including this, this, and this, and several other videos, but am still struggling.