Updated April 14, 2023
We can see that after using bind for your function it results in the creation of a new function that is bounded. The execution of the bounded function will result in the calling of the wrapped function that wraps the original function object.
The syntax of the bind function is as defined below:
let boundedFunction = mainFunction.bind(argumentForThis[,argument1[,argument2[,...argumentN]]])
- argument1[, argument2[, …argumentN – These are the additional arguments that you want to pass to the target function main function in our case. This is further prepended to the new function created a bounded function. This is optional in nature.
- boundedFunction – This is the new function that is returned and is a copy of the original main function with the specified value of the “this” keyword as the first argument and other arguments values as the initial value provided if they are mentioned.
We can observe from the above example that the first method in which the function is called directly using the name of the object the output we get is the correct one saying address as Hinjewadi, Pune, and name of office as XYZ. The “this” keyword refers to the object office in our first call… In the second example, when we use the reference of the property of the object to call the function the output varies and the address and name are retrieved as undefined as the scope changes to the global context, and the “this” now refers on the global scope.
Now, let us see, how we can use the bind() method to solve our issue by using the same example.
that results in the following output after execution –