JavaScript call, bind, and apply methods
Tags: javascript, webdev, node
Published: 2020-11-28 18:48:38

Full post available [here](https://taslangraham.com/2020/11/28/js-call-bind-and-apply-methods/).
<!-- wp:paragraph -->
<p>Each JavaScript function has access to the <em>this </em>keyword. The <em>this </em>keyword references the object to which the function belongs (remember, everything in JS is an Object). </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>This sounds straightforward enough but, things can quickly get tricky when working with <em>this.</em> Why? The value of <em>this</em> is determined by how/where the function was executed:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul id="block-b8cac825-336b-46ce-bbc7-5430c6799d15"><li>In a method,&nbsp;<em>this</em>&nbsp;refers to the&nbsp;<strong>owner object</strong>.</li><li>Alone,&nbsp;<em>this</em>&nbsp;refers to the&nbsp;<strong>global object</strong>.</li><li>In a function,&nbsp;<em>this</em>&nbsp;refers to the&nbsp;<strong>global object</strong>.</li><li>In a function, in strict mode,&nbsp;<em>this </em>is&nbsp;<em>undefined</em></li><li>In an event,<em> this </em>refers to the&nbsp;<strong>element</strong>&nbsp;that received the event.</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>This means that if we are not careful we can lose the scope of <em><strong>this</strong></em>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Luckily, all JavaScript function object has access to some very special methods which we can use to explicitly state what <em><strong>this </strong></em>should reference. These methods are <em><strong>bind()</strong>, <strong>call()</strong>,  &amp; <strong>apply()</strong></em>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p></p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2><br>Bind</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p><br>The&nbsp;<em><strong>bind()</strong></em>&nbsp;method creates a new function that, when called, has its&nbsp;<strong><em>this</em>&nbsp;</strong>keyword reference the provided value.</p>
<!-- /wp:paragraph -->

``` javascript

function greeting() {
  console.log(`${this.firstName} says hi!`)
}

const john = {
  firstName: 'John',
  lastName: 'Doe',
  age: 20
};

const johnGreeting = greeting.bind(john);
```
<!-- wp:paragraph -->
<p><br>Above, we created the function <em>greeting</em>, then on line <em>11</em>, we used the <strong><em>bind </em> </strong>method to tell the function that the <em><strong>this </strong></em>keyword should point to the object <em><strong>john</strong></em>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>This then returns a new function which we store inside <em><strong>johnGreeting</strong></em>. We can then execute <em><strong>johnGreeting</strong></em>.</p>
<!-- /wp:paragraph -->

``` javascript
johnGreeting(); // John says hi!
```

<!-- wp:paragraph -->
<p></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The <em><strong>bind()</strong> </em>method can also accept arguments. These will come after the <strong><em>this</em> </strong>argument. Here's an example:</p>
<!-- /wp:paragraph -->

``` javascript
function greeting(country) {
  console.log(`${this.firstName} says hi! from ${country}`)
}

const john = {
  firstName: 'John',
  lastName: 'Doe',
  age: 20
};
```
</pre>
<!-- /wp:syntaxhighlighter/code -->

<!-- wp:paragraph -->
<p></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Here our greeting function now accepts an argument, <em>country</em>. We can now pass an additional parameter to the <em><strong>bind()</strong></em> method.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p></p>
<!-- /wp:paragraph -->



```javascript
const johnGreeting = greeting.bind(john, 'Jamaica');
 
johnGreeting(); // John says hi! from Jamaica

```


<!-- wp:heading -->
<h2><br>Call</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p><br>The&nbsp;<em><strong>call()</strong></em>&nbsp;method calls a function with a given&nbsp;<em><strong>this</strong></em>. The difference between the <em><strong>bind()</strong></em><strong> </strong>and the <em><strong>call()</strong></em> is that the <em><strong>call()</strong></em> method does not create a new function, instead it immediately executes the function. Here's an example:</p>
<!-- /wp:paragraph -->

``` javascript
function printName() {
  console.log(`${this.firstName} ${this.lastName}`);
}

student = {
  firstName: 'Taslan',
  lastName: 'Graham'
};

printName.call(student);// Taslan Graham
```

<!-- wp:paragraph -->
<p></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Here we created a function, <em><strong>printName</strong></em>, and an object <em><strong>student</strong></em>. We then, on line 10, executed the <strong><em>printName</em> </strong>function by calling the <strong>call() </strong>method on it and passing student object as the <strong><em>this</em> </strong>that <em><strong>printName </strong></em>should use.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Similarly to the <em><strong>bind()</strong></em> method, the <em><strong>call()</strong> </em>method can accept arguments.</p>
<!-- /wp:paragraph -->

``` javascript
function printName(age) {
  console.log(`Name: ${this.firstName} ${this.lastName}, Age:${age}`);
}

student = {
  firstName: 'Taslan',
  lastName: 'Graham'
};

printName.call(student, 24); // Name: Taslan Graham, Age:24

```
 <p>Here our greeting function now accepts an argument,&nbsp;<em>age</em>. We can now pass an additional parameter to the&nbsp;<em><strong>call()</strong></em>&nbsp;method.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2><br>Apply<br></h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p><br>Like the the methods above,  the <em><strong>apply()</strong></em> method calls a function with a given&nbsp;<em><strong>this</strong></em>. It is very similar to the <em><strong>call()</strong></em>  method, the difference being that the <em><strong>apply()</strong> </em>method accepts arguments as an array.</p>
<!-- /wp:paragraph -->


```javascript
const student = {
  details: function () {
    return `${this.name}, ${this.class}`;
  }
}

const graham = {
  name: "Graham",
  class: "Intro to Computer Science",
}
 
console.log(student.details.apply(graham)); // Graham, Intro to Computer Science
```

<!-- wp:paragraph -->
<p></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Here we have an object, <em><strong>student</strong></em>, which has a method called <em><strong>details</strong></em>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We also have another object, <em><strong>graham</strong></em>, this object does not have the <strong><em>details</em> </strong>method, but we used the <em><strong>apply()</strong> </em> method to tell the the <em><strong>details()</strong> </em>method of <strong><em>student</em> </strong>that its <em><strong>this </strong></em>value should point to the the <strong><em>graham</em> </strong>object.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><em><span style="text-decoration:underline;">Note: bind() &amp; call() can be used in the way apply() is used aboved. </span></em></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The <em><strong>apply()</strong></em> method can also accept additional arguments. These are passed as an array. </p>
<!-- /wp:paragraph -->


```javascript
function printName(...args) {
  console.log(`Name: ${this.firstName} ${this.lastName}, Age:${args[0]} Country: ${args[1]}`);
}

student = {
  firstName: 'Taslan',
  lastName: 'Graham'
};

const age = 24;
const country = "Jamaica";
printName.apply(student, [age, country]); // Name: Taslan Graham, Age:24 Country: Jamaica
```


<!-- wp:paragraph -->
<p></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Above, we passed an array holding <em>age </em>and <em>country </em>to our <em><strong>printName </strong></em>function. We use the <a rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters" target="_blank">rest parameters</a> to capture this array, then we print the values from their respective indexes. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><br><br>As you can see, the <em><strong>bind()</strong></em>, <strong><em>call()</em>,</strong><em>  <strong>bind()</strong></em> are very powerful when we want want to determine what  the <strong><em>this </em></strong>value inside of a function should be. They all work similarly but with there own unique differences. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The <strong><em>bind()</em></strong> method creates a new function with the <strong>this</strong><em> </em>value provided to it. While the <strong><em>call()</em></strong> method immediately executes a function with the given <strong><em>this</em></strong> value. Similarly to  the <strong><em>call()</em></strong> method, <strong><em>apply()</em></strong> immediately executes the function with the given <strong><em>this</em></strong> value but, it accepts its arguments as an array.<br><br>Hope you found this helpful. Be sure to leave comments below on the interesting ways you've used <em>call(), bind(), and apply()</em>.<br><br>Until next time, <em>think, learn, create, repeat!</em></p>
<!-- /wp:paragraph -->