You can find previous part of this series here.
We already know that a function is a special type of object and has several properties, we already discussed it. To better understand what we are going to deal with today, let's start with an example.
After inwoking a function, we will receive.
What's wrong here?
In that case, wouldn't it be nice and pleasant to have such access?
In the example above, we used the bind function.
Thanks to this function, all we did was that we combined Function Expression logName with the person Object, and the whole thing was saved in the logPersonName variable. But how does it really work? Well, the bind function creates a new copy of the logName function. By passing the object, person, we have an influence on what we want our copy to "combine" with. The this variable in the logName Function Expression will refer to the object that we passed. As it is really only a copy, we can invoke it, as we do in the eighteenth line.
As you can see, this is quite useful when you want to access the object in a function outside that object.
This function is very similar to the bind.
As you can see, we called the call function on logName and passed the person.
The result will be identical but in this case, no copy of the logName function is created, but the logName function itself is invoked. In fact, logName.call is the same as logName(), which is invoking a function. However, using the call function we have a greater ability to influence what we want to achieve, we have an influence on whether this variable is. Of course, we can also pass two arguments to the parameters part1 and part2.
Here we have another function that is similar to the rest. Using it, we also control what the special variable this is supposed to be, but we pass the arguments in an array.
Probably now the question comes to mind, what is the actual use of it in real life?
The first case is the so-called function borrowing.
Here you can observe that despite using the getFullName method on the person object, we received "Tom Goe". This is because we have manipulated what the special variable this is. As the return value from the getFullName method is the variable fullName, and in it we indicate through variable this that firstName and lastName are to refer to the object on which it is called.
The next case is the function currying.
This example is related to bind, because then a copy of the function is created.
It is also not complicated.
In the bind function, first of all, we pass to what the special variable this is supposed to refer to. Then we set permamentally what will be the first parameter, in our case a. As the result a * b is returned, and a is always equal 2. At the time of the invocation of the function, we give only what b parameter should be equal to.
Of course, if we passed 10 instead of 5, we would get 20. And so on.