Code please explain to JS(comments,if possible).Especially interested in why is this?

Write a function applyAll(func, arg1, arg2,...) which accepts a function func and an arbitrary number of arguments.

It should call func(arg1, arg2...), that is to pass in a func of all the arguments, starting with the second and return the result.

function sum() {
return [].reduce.call(arguments, function(a, b) {
return a + b;
});
}

function mul() {
return [].reduce.call(arguments, function(a, b) {
return a * b;
});
}

function applyAll(func) {
return func.apply(this, [].slice.call(arguments, 1));
}

alert( applyAll(sum, 1, 2, 3) ); // 6
alert( applyAll(mul, 2, 3, 4) ); // 24
alert( applyAll(Math.max, 2, -2, 3) ); // 3
alert( applyAll(Math.min, 2, -2, 3) ); // -2
June 8th 19 at 17:30
2 answers
June 8th 19 at 17:32
https://learn.javascript.ru/call-apply
I advise you to study the whole section on "object Methods and the calling context".
June 8th 19 at 17:34
this in this example is not necessary, can be replaced by anything is null, 1, NaN, undefined...
The rest of this code assumes rather crutches around arguments rather than the application calling context.
Now the only thing that you need to know about "arguments" - never to use it.
In modern js this code might look something like this:
function sum(...args) {
 return args.reduce((acc, val) => acc + val);
}

function mul(...args) {
 return args.reduce((acc, val) => acc * val);
}

function applyAll(func, ...values) {
 return func(...values);
}

alert( applyAll(sum, 1, 2, 3) ); // 6
alert( applyAll(mul, 2, 3, 4) ); // 24
alert( applyAll(Math.max, 2, -2, 3) ); // 3
alert( applyAll(Math.min, 2, -2, 3) ); // -2
OK,but what is this or null, or 1 or NAN or undefined? - deangelo_Pacocha commented on June 8th 19 at 17:37
in this task, for anything. Just the apply function, the first argument takes the context of the call, the second is an array of arguments. The context here is not important, so the first argument is passed anything, usually null.
In other words, this task uses only the ability the apply method to deploy the array of arguments in the argument list for the invoked function. - oleta.Wi commented on June 8th 19 at 17:40

Find more questions by tags JavaScript