What Is the Difference Between Call, Apply, and Bind in JavaScript?
<p>JavaScript is a wonderful and wild language, full of hidden gems and quirky features that can make even seasoned developers raise an eyebrow.</p>
<p>Today, we’re going to examine some built-in functions of JavaScript’s Function prototype with three essential methods: <code>call</code>, <code>apply</code>, and <code>bind</code>.</p>
<p>These three musketeers are powerful tools when it comes to function invocation and changing the context of <code>this</code> inside a function. But when should you use each of them? Let’s find out! </p>
<h1>Picking Up the Pace with <code>call</code> </h1>
<p>The <code>call</code> method is all about invoking a function with a specific <code>this</code> context and passing in arguments one by one.</p>
<blockquote>
<p>The <code>call()</code> method of <code>Function</code> instances calls this function with a given <code>this</code> value and arguments provided individually.<br />
— MDN Docs</p>
</blockquote>
<p>Think of it as a runner in a relay race , carrying the baton (the <code>this</code> value) and passing it on. Here's a quick example:</p>
<pre>
function introduce(firstName, lastName) {
console.log(`Hello, my name is ${this.title} ${firstName} ${lastName}.`)
}
const person = {
title: "Dr."
};
introduce.call(person, "Derek", "A") // "Hello, my name is Dr. Derek A."</pre>
<h1>Blasting Off with <code>apply</code> </h1>
<p>Next up is the <code>apply</code> method, which, much like its sibling <code>call</code>, allows you to invoke a function with a specific <code>this</code> context.</p>
<p><a href="https://medium.com/just-javascript-tutorials/what-is-the-difference-between-call-apply-and-bind-in-javascript-595b45333cc0">Website</a></p>