This content originally appeared on Level Up Coding - Medium and was authored by Kyle Le
Introduction
Apply — Call — Bind are the three methods in JavaScript used to set the context and arguments when calling functions
Understand the usage of these methods can be very useful in technical interviews.
Bind
First is the bind method, let’s look at this piece of code:
const dog = {
name: 'Cloud',
speak(sound) {
return `${this.name} says ${sound}`
}
}
dog.speak("Grr"); //returns 'Cloud says Grr'
Which is easy to understand, I have a dog object, I have a property name and a method speak that uses the name property.
Now, I will create another function from the dog.speak :
const dogSpeak = dog.speak
dogSpeak('Grr') //return 'undefined says Grr'
The name property is now undefined , because the context of the cat object is lost. But we can prevent this by calling bind method
const dogSpeak = dog.speak.bind(dog)
dogSpeak('Grr') //return 'Cloud says Grr'
The result is correct now, because we bind dog as the context, so dog will become this .
Reminder: You can pass any object to the bind method as the context, for instance if I pass { name: 'Leon' } it would still return Leon says Grr
Call
In the example above, we already understand that bind returns a function.
While call immediately calls the function:
const dogSpeak = dog.speak.call(dog, 'Grr') //return 'Cloud says Grr'
That’s just it, understandable, right guys ?
Apply
We already understand that bind accepts the this context and its method arguments like bind(this, arg1, arg2)
But with apply , the only thing that changes is apply accept the arguments as an array like apply(this, [arg1, arg2)
Conclusion
Thanks for reading this, the article is pretty short and I tried my best to keep it as simple as it can be.
Last Words
Although my content is free for everyone, but if you find this article helpful, you can buy me a coffee here
Level Up Coding
Thanks for being a part of our community! Before you go:
- 👏 Clap for the story and follow the author 👉
- 📰 View more content in the Level Up Coding publication
- 🔔 Follow us: Twitter | LinkedIn | Newsletter
🚀👉 Join the Level Up talent collective and find an amazing job
Understand Apply Bind Call in JavaScript in 3 minutes was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Level Up Coding - Medium and was authored by Kyle Le
Kyle Le | Sciencx (2023-01-29T11:47:06+00:00) Understand Apply Bind Call in JavaScript in 3 minutes. Retrieved from https://www.scien.cx/2023/01/29/understand-apply-bind-call-in-javascript-in-3-minutes/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.