Updated April 13, 2023
We can see that after using apply for your function it results in the calling of the function with the specified argument to be referenced by the “this” keyword and the arguments are passed to the function as specified in the array in the second parameter. The syntax of the apply function is as defined below –
- Return value: The output of calling 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 in the array parameter or array-like parameter if they are mentioned.
The apply() method helps us to write the function once and make the use that function by inheriting it by multiple objects. That means a single function can be used by more than one object by specifying the different values i.e object reference as the first parameter of the apply method. The value of “this” can be specified at the time of the calling of a function.
Consider a simple example to get a hold on the sayings mentioned above.
We can observe that the company1 records are fetched and the “this” keyword references to the company1 object because we have mentioned it as the first parameter. Similarly, if we would have used
var temporaryVariable = company.fullName.call(company2, "Paul Hermelin", 15000);
instead of company1 we would have got the following output because now the “this” will refer to the company2 object.
We can use the apply method whose full name is Function.prototype.apply() for creating the functions that can be used by multiple objects by simply inheriting them in other objects. There is no need to rewrite the same function for multiple objects. What you need to do is simply mention the value or object to be referenced by the “this” keyword as the first parameter to the apply() method.