<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Ayilara Sodiq</title>
    <description>The latest articles on DEV Community by Ayilara Sodiq (@drayilara).</description>
    <link>https://dev.to/drayilara</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F621501%2F8fe79a95-ecb5-4d18-967e-5c4a5e523866.jpg</url>
      <title>DEV Community: Ayilara Sodiq</title>
      <link>https://dev.to/drayilara</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/drayilara"/>
    <language>en</language>
    <item>
      <title>this in JavaScript. The only article you need to read.</title>
      <dc:creator>Ayilara Sodiq</dc:creator>
      <pubDate>Tue, 22 Mar 2022 11:37:27 +0000</pubDate>
      <link>https://dev.to/drayilara/this-in-javascript-the-only-article-you-need-to-read-3m9b</link>
      <guid>https://dev.to/drayilara/this-in-javascript-the-only-article-you-need-to-read-3m9b</guid>
      <description>&lt;p&gt;If you are like me, you have spent several hours trying to understand &lt;em&gt;&lt;strong&gt;this&lt;/strong&gt;&lt;/em&gt;. You have heard terms like, a function binds its own &lt;em&gt;&lt;strong&gt;this&lt;/strong&gt;&lt;/em&gt;, and you didn't get it. I have been there, that is why I am writing this article. The goal is to help you understand the concept in simple, clear terms.&lt;/p&gt;

&lt;p&gt;This article is targeted at the following groups:&lt;br&gt;
• junior developers&lt;br&gt;
• senior developers&lt;/p&gt;

&lt;p&gt;The following are the prerequisite knowledge required:&lt;br&gt;
• Functions in JavaScript&lt;br&gt;
• An understanding of the window object&lt;br&gt;
• Class syntax in JavaScript&lt;br&gt;
• Objects in JavaScript&lt;br&gt;
• Event listeners in JavaScript&lt;/p&gt;

&lt;p&gt;This article does not cover advanced edge cases of the this keyword, please read the docs here: &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this"&gt;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The article is in two parts:&lt;/p&gt;

&lt;p&gt;Part 1, discusses the everyday use of this:&lt;br&gt;
• what is this&lt;br&gt;
• this in regular functions&lt;/p&gt;

&lt;p&gt;Part 2 covers the following:&lt;br&gt;
• this in arrow functions&lt;br&gt;
• this in special cases&lt;/p&gt;

&lt;p&gt;What is &lt;code&gt;this&lt;/code&gt;? &lt;code&gt;this&lt;/code&gt; is a special keyword in JavaScript. &lt;em&gt;It always refers to an object, without exception&lt;/em&gt;. So, we have solved the first part, this is a pointer in JavaScript. Onward, we go. The second part, &lt;em&gt;this is always declared in a function&lt;/em&gt;. This is key to understanding &lt;code&gt;this&lt;/code&gt;. For clarity, here are the rules again:&lt;/p&gt;

&lt;p&gt;• this is always a pointer to an object.&lt;br&gt;
• this is always defined inside a function.&lt;/p&gt;

&lt;p&gt;Let's see a quick example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let obj = {

country : 'nigeria',

getCountry(){
return this.country;
}
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Don't worry about the code, it will be explained, just observe that &lt;code&gt;this&lt;/code&gt; is in a function, and it refers to the object- &lt;code&gt;obj&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Regular functions(for simplicity, will refer to any function other than arrow functions) and &lt;code&gt;this&lt;/code&gt;. Read closely here. When &lt;code&gt;this&lt;/code&gt;is defined in a regular function, it points to the object that invokes the function. In other words, it points to the object which called the function. This means that &lt;code&gt;this&lt;/code&gt; in a regular function is NOT sure what to point to until the function is invoked. Consider the simple example above:&lt;/p&gt;

&lt;p&gt;• A function inside an object like this is called a method.&lt;/p&gt;

&lt;p&gt;• &lt;code&gt;this&lt;/code&gt; in the &lt;code&gt;getCountry&lt;/code&gt; function doesn't know what object to point to just yet, it's as confused as you and I.&lt;/p&gt;

&lt;p&gt;• the value of &lt;code&gt;this&lt;/code&gt; becomes clear to JavaScript, when you invoke(run or call) the function.&lt;/p&gt;

&lt;p&gt;• the value of &lt;code&gt;this&lt;/code&gt;, is set to the object that directly calls the function.&lt;/p&gt;

&lt;p&gt;• So, to call the &lt;code&gt;getCountry&lt;/code&gt; method, we write:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;obj.getCountry();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;• Guess what this refers to.&lt;/p&gt;

&lt;p&gt;• Yes, it refers to the &lt;code&gt;obj&lt;/code&gt; object, as it was the object that called the function &lt;code&gt;getCountry.&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;• Hence, the output will be: nigeria.&lt;/p&gt;

&lt;p&gt;Let's consider something more interesting. Given the following expressions, determine the output, and explain why. Try this yourself, before seeing my explanation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;First example:

function logger(str){
    return this.str;
}

logger(‘John’) // ??

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Second example:

let obj = {
  name : 'John',

  getName(){

    function anotherFunc(){
      return this.name;
    }

    return anotherFunc();
  }
}

obj.getName() // ??

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;How did that go? It doesn't matter, so long you tried. Now, let's consider the first example:&lt;/p&gt;

&lt;p&gt;• When you call the function, &lt;code&gt;logger&lt;/code&gt;, what happens?&lt;/p&gt;

&lt;p&gt;• All JavaScript functions run within an object behind the scenes. This object is referred to as the &lt;em&gt;&lt;strong&gt;context of the function&lt;/strong&gt;&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;• &lt;em&gt;&lt;strong&gt;A little trick, to determine the context of a function is to look to the left of the function when it is invoked.&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;• &lt;code&gt;this&lt;/code&gt;always refers to the context.&lt;/p&gt;

&lt;p&gt;• To call the &lt;code&gt;logger&lt;/code&gt; function, we write &lt;code&gt;logger();&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;• In reality, this is is what is happening : &lt;code&gt;window.logger();&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;• This is because the &lt;code&gt;window&lt;/code&gt;object is the closest object to the function, hence it is its context.&lt;/p&gt;

&lt;p&gt;• The function logs &lt;code&gt;undefined&lt;/code&gt;, as the &lt;code&gt;str&lt;/code&gt; property doesn't exist on the window object.&lt;/p&gt;

&lt;p&gt;• If we remove the &lt;code&gt;str&lt;/code&gt;parameter from the function, and just return &lt;code&gt;this&lt;/code&gt;, you get the &lt;code&gt;window&lt;/code&gt;object.&lt;/p&gt;

&lt;p&gt;In this second example, to access the &lt;code&gt;getName&lt;/code&gt; method, we write &lt;code&gt;obj.getName()&lt;/code&gt;,but we get &lt;code&gt;undefined&lt;/code&gt; as our result. This happens because our method returns another function. A function nested inside of the &lt;code&gt;getName&lt;/code&gt; method- a nested function. The nested function is the one with &lt;code&gt;this&lt;/code&gt;.&lt;br&gt;
What does &lt;code&gt;this&lt;/code&gt; point to? Well, let's try to call the nested function and then look left.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;obj.getName.anotherFunc()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, the closest caller of the &lt;code&gt;anotherFunc&lt;/code&gt; function is not an object but a method: &lt;code&gt;getName&lt;/code&gt;. But &lt;code&gt;this&lt;/code&gt; doesn't point to a function, ever. What is really happening?&lt;br&gt;
Well, this is it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;obj.getName.window.anotherfunc
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Hence the object closest to &lt;code&gt;anotherFunc&lt;/code&gt; is the window.&lt;br&gt;
This object doesn't have a name property on it, so it returns &lt;code&gt;undefined&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This logic is true for all regular functions nested in a method, no matter how deep the nesting, the context is always the window object. You can try this out yourself.&lt;/p&gt;

&lt;p&gt;We have discussed some key concepts thus far, I advise you to practice some questions at this point to test your understanding.&lt;br&gt;
Try these two(answers are immediately after both questions):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Question 1:

const object = {
  message: 'Hello, World!',
  getMessage() {
    const message = 'Hello, Earth!';
    return this.message;
  }
};
console.log(object.getMessage()); // What is logged?
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Question 2:

const object = {
  message: 'Hello, World!'
};

function logMessage() {
  console.log(this.message); // 
}

logMessage();  // ??

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;These questions are gotten from Dmitri Pavlutin, you can check out his blog here for more : &lt;a href="https://dmitripavlutin.com/javascript-this-interview-questions/"&gt;https://dmitripavlutin.com/javascript-this-interview-questions/&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Answer to question 1:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Hello, World!&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Answer to question 2:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;undefined&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The concepts that we have discussed so far are the natural ways this works. This is what is called &lt;em&gt;implicit binding&lt;/em&gt; of this. But sometimes, we want to force &lt;code&gt;this&lt;/code&gt; to behave in a more flexible manner. For example, in the &lt;code&gt;anotherFunc&lt;/code&gt; above, say we want &lt;code&gt;this&lt;/code&gt; to point &lt;code&gt;obj&lt;/code&gt;, rather than the &lt;code&gt;window&lt;/code&gt; object. Well, we must &lt;em&gt;explicitly&lt;/em&gt; tell JavaScript to do that.&lt;/p&gt;

&lt;p&gt;Explicit this binding can be achieved in one of three simple ways:&lt;/p&gt;

&lt;p&gt;• &lt;code&gt;call&lt;/code&gt;(context, arg)&lt;br&gt;
• &lt;code&gt;apply&lt;/code&gt;(context, [arg])&lt;br&gt;
• &lt;code&gt;bind&lt;/code&gt;(context, arg)&lt;/p&gt;

&lt;p&gt;The call method is applied to a function to change the context of the function i.e to change what &lt;code&gt;this&lt;/code&gt; is points to. We can change it to whatever we like.&lt;/p&gt;

&lt;p&gt;To change &lt;code&gt;anotherFunc&lt;/code&gt; to reference our &lt;code&gt;obj&lt;/code&gt;object, we reframe our object like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let obj = {
  name : 'John',
  getName(){

    function anotherFunc(){
      return this.name;
    }
    return anotherFunc.call(obj);
  }
}

obj.getName() // "John"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The second parameter of the call method is &lt;code&gt;args&lt;/code&gt;, which refers to the argument you want to pass into the function. Here is an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function welcome(event){
  return 'Hello ' + this.name + ' welcome to the ' + event
}

let obj = {
  name : 'John'
}

welcome.call(obj,'Oscars'); //

'Hello John welcome to the Oscars'

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The apply method works exactly like the call method ,except it takes &lt;code&gt;args&lt;/code&gt; in the form of an array. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function welcome(a, b, c){
  console.log('Hello ' + this.name + ' welcome to the ' + a);
  console.log('Hello ' + this.name + ' welcome to the ' + b);
  console.log('Hello ' + this.name + ' welcome to the ' + c);
}

let obj = {
  name : 'John'
}

let events = ['Grammy', 'Oscars', 'World cup'];

welcome.apply(obj, events);

// Hello John welcome to the Grammy
// Hello John welcome to the Oscars
// Hello John welcome to the World cup


//a, b, and c ---&amp;gt; the indices of the events elements.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The bind method works like the call method, however it returns a new function that can be called later. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function welcome(event){
  return 'Hello ' + this.name + ' welcome to the ' + event
}

let obj = {
  name : 'John'
}

let bindFunc = welcome.bind(obj,'Oscars'); 

bindFunc(); //


'Hello John welcome to the Oscars'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I hope this article, has clarified this for you. Part 2 will go into some quirky parts of &lt;code&gt;this&lt;/code&gt;, for now, cheers and see you soon.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>beginners</category>
      <category>webdev</category>
      <category>programming</category>
    </item>
  </channel>
</rss>
