The Call And Apply Methods In JS: Hello everyone, welcome to the nkcoderz.com website. In this article we will going to discuss about the The Call And Apply Methods In JS.
The Call And Apply Methods In JS
In JavaScript, both call
and apply
are methods available on all functions and allow you to invoke a function and set the this
value within that function to a specific object.
The call
method takes in the object that you want to be this
, followed by any arguments to pass to the function being invoked.
Code For Apply Method In JS
Example:
function greet(greeting, punctuation) {
return greeting + ' ' + this.name + punctuation;
}
let person = { name: 'John Doe' };
greet.call(person, 'Hello', '!');
Output
“Hello John Doe!”
The apply
method works similarly, but it takes in the object that you want to be this
as the first argument, and the arguments to pass to the function as an array.
Code For apply Method In JS
Example:
function greet(greeting, punctuation) {
return greeting + ' ' + this.name + punctuation;
}
let person = { name: 'John Doe' };
greet.apply(person, ['Hello', '!']); //
Output
“Hello John Doe!”
Both call
and apply
allow you to pass arguments to a function in a dynamic way and can be useful in various scenarios such as:
- Borrowing methods: You can use
call
orapply
to invoke a method belonging to one object on another object. - Implementing inheritance: You can use
call
orapply
to chain constructors for an object, which can be used to implement inheritance. - Setting the
this
value explicitly: As mentioned earlier, you can usecall
orapply
to set thethis
value explicitly, which can be useful in event handling, array processing, and more. - Currying: You can use
call
orapply
to create a new function with some arguments pre-filled, which is called currying.
In summary, call
and apply
provide a flexible way to invoke a function and set the value of this
, and they can be used in various scenarios where you need to manipulate the arguments passed to a function.
Conclusion
If you liked this post The Call And Apply Methods In JS, then please share this with your friends and make sure to bookmark this website for more awesome content.