First, one must understand what the function is compose
which is implemented by the code. Note that it expects two arguments (two functions) and will return a new function - a composite function created from the composition of the two provided.
Note that the function compose
returns a new function (the composite function):
function compose(f, g) {
// Essa função é o resultado da composição de `f` e `g`.
// Está sendo retornada.
return function () {
// ...
};
}
But note that this function being returned does not explicitly wait for any argument. So how can we call squareofsum
passing arguments like 2
and 3
? The arguments are being obtained from the object array-like arguments
.
Looking a little deeper, we now come to this expression, which is the first to be evaluated:
g.apply(this, arguments);
She’s basically calling the function g
passing the arguments you passed to the composite function. How arguments
is an object array-like, the apply
is ideal in this case, since apply
accepts, in its second argument, an array of ordered parameters to be passed during the function application.
See this simple example to understand what happens:
function myFunc() {
console.log(arguments);
// Aplicaremos os argumentos à `console.log`:
console.log.apply(console, arguments);
}
myFunc(1, 2, 3);
With that, the expression g.apply(this, arguments)
return the function value g
when applied using the arguments passed to the composite function.
Then this returned value will be used as argument for the function f
. More simply, what is happening is this:
function compose(f, g) {
return function () {
const resultOfG = g.apply(this, arguments);
return f.call(this, resultOfG);
};
}
In short, this method of functional composition is basically to call f
as a result of the application of g
with some arguments. Something like this:
f(g(2, 3));
As a curiosity, the syntactic construction ...
(in this context called parameters Rest) can make the use of arguments
unnecessary most of the time. Another way to implement that compose
is:
function compose(f, g) {
return function (...args) {
return f(g(...args));
};
}
This answers your question? What’s the difference between apply, call and bind methods when calling a function in Javascript?
– Cmte Cardeal
no, I know how it works I just could not understand what the logic of these methods in function.
– Bruno Coelho