{"id":3410,"date":"2022-08-09T07:13:44","date_gmt":"2022-08-09T12:13:44","guid":{"rendered":"https:\/\/www.becomebetterprogrammer.com\/?p=3410&#038;preview=true&#038;preview_id=3410"},"modified":"2022-08-09T07:23:41","modified_gmt":"2022-08-09T12:23:41","slug":"javascript-this-keyword","status":"publish","type":"post","link":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-this-keyword\/","title":{"rendered":"JavaScript | Complete Guide to Understanding &#8220;This&#8221; Keyword"},"content":{"rendered":"\n<p>Javascript is becoming more popular for building web applications and mobile apps using React Native framework. Therefore, understanding its key concepts can come in quite handy. The &#8220;<em>this<\/em>&#8221; keyword in Javascript is a source of confusion and misery for most beginner Javascript developers and even pro-developers. This post aims to give you a beginner-friendly comprehensive guide on &#8220;<em>this<\/em>&#8221; keyword in Javascript.<\/p>\n\n\n\n<p><strong>The &#8220;this&#8221; keyword in Javascript refers to the object that owns the Javascript function currently being executed. In other words, &#8220;this&#8221; is a reference to the current execution context of the function.<\/strong><\/p>\n\n\n\n<p>Don&#8217;t panic if you find this definition a little complex to grasp. This post will break down the &#8220;this&#8221; keyword into smaller bits that you can easily understand. It will also include code snippets that will give you a deeper understanding of how to use &#8220;this&#8221; in your Javascript code. <\/p>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_82_2 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\"><p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<\/div><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-this-keyword\/#Execution_Context\" >Execution Context<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-this-keyword\/#What_is_%E2%80%9Cthis%E2%80%9C\" >What is &#8220;this&#8220;?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-this-keyword\/#%E2%80%9Cthis%E2%80%9D_in_the_Global_Context\" >&#8220;this&#8221; in the Global Context<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-this-keyword\/#%E2%80%9Cthis%E2%80%9D_in_Function_Context\" >&#8220;this&#8221; in Function Context<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-this-keyword\/#%E2%80%9Cthis%E2%80%9D_in_a_Function_without_strict_mode\" >&#8220;this&#8221; in a Function (without strict mode)<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-this-keyword\/#%E2%80%9Cthis%E2%80%9D_in_a_Function_with_strict_mode\" >&#8220;this&#8221; in a Function (with strict mode)<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-this-keyword\/#%E2%80%9Cthis%E2%80%9D_in_Function_Method_Context\" >&#8220;this&#8221; in Function Method Context<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-this-keyword\/#%E2%80%9Cthis%E2%80%9D_in_Arrow_Functions\" >&#8220;this&#8221; in Arrow Functions<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-this-keyword\/#%E2%80%9Cthis%E2%80%9D_With_the_Call_and_Apply_Methods\" >&#8220;this&#8221; With the Call and Apply Methods<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-this-keyword\/#%E2%80%9Cthis%E2%80%9D_with_the_Bind_Method\" >&#8220;this&#8221; with the Bind() Method<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-this-keyword\/#%E2%80%9Cthis%E2%80%9D_in_Callback_Functions_Problem\" >&#8220;this&#8221; in Callback Functions (Problem)<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-this-keyword\/#Solution_1_Explicitly_setting_%E2%80%9Cthis%E2%80%9C\" >Solution 1: Explicitly setting &#8220;this.&#8220;<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-this-keyword\/#Solution_2_Using_Arrow_Functions\" >Solution 2: Using Arrow Functions<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-14\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-this-keyword\/#Solution_3_Using_the_Bind_Method\" >Solution 3: Using the Bind() Method<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-15\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-this-keyword\/#%E2%80%9Cthis%E2%80%9D_in_Constructor_Functions\" >&#8220;this&#8221; in Constructor Functions<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-16\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-this-keyword\/#%E2%80%9Cthis%E2%80%9D_in_Event_Handlers\" >&#8220;this&#8221;&nbsp;in Event Handlers<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-17\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-this-keyword\/#%E2%80%9Cthis%E2%80%9D_Keyword_Precedence\" >&#8220;this&#8221; Keyword&nbsp;Precedence<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-18\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-this-keyword\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Execution_Context\"><\/span>Execution Context<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>One of the statements used to define &#8220;this&#8221; keyword in this post is,  <em>&#8220;whenever a function is executing in Javascript, it has a reference to its <strong>current execution context<\/strong> &#8211; called &#8220;<strong>this<\/strong>.&#8221;<\/em> So, what is <a href=\"https:\/\/www.freecodecamp.org\/news\/execution-context-how-javascript-works-behind-the-scenes\" target=\"_blank\" rel=\"noopener\">Execution Context<\/a>? And how does it relate to the &#8220;this&#8221; keyword?<\/p>\n\n\n\n<p><strong>The execution context is like a wrapper (<em>or a box<\/em>) in which your Javascript code executes. It contains information and details about the environment of the current code in execution. <\/strong><\/p>\n\n\n\n<p>This post will use the Global Execution Context (GEC) as an example to understand the term Execution Context better. GEC is the default execution context where all Javascript code outside a function is executed. See the illustration below of the Global Execution Context.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"519\" src=\"https:\/\/www.becomebetterprogrammer.com\/wp-content\/uploads\/2022\/08\/The-Global-Execution-Context-1024x519.png\" alt=\"\" class=\"wp-image-3421\" srcset=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/08\/The-Global-Execution-Context-1024x519.png 1024w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/08\/The-Global-Execution-Context-300x152.png 300w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/08\/The-Global-Execution-Context.png 1508w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption>Global Execution Context<\/figcaption><\/figure>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Global Objec<\/strong>t: That is the object that exists in the Global Scope. In this case, it&#8217;s the browser window object.<\/li><li>&#8220;<strong>This<\/strong>&#8220;: The &#8220;this&#8221; keyword is a variable provided in every execution context and refers to the object currently executing your bit of Javascript code. In this case &#8211; it refers to the &#8220;global object.&#8221; On a browser, that would be the &#8220;window object.&#8221; In NodeJS, it would be the special object called &#8216;global.&#8217;<\/li><li><strong>Variable Environmen<\/strong>t: Also known as &#8220;memory.&#8221; It stores all the variables and functions in your code as key-value pairs.<\/li><li><strong>Outer Environment<\/strong>: Every execution context has a reference to the outer environment, also known as the <a href=\"https:\/\/amnsingh.medium.com\/lexical-environment-the-hidden-part-to-understand-closures-71d60efac0e0\" target=\"_blank\" rel=\"noopener\">Lexical Environment<\/a>.<\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"What_is_%E2%80%9Cthis%E2%80%9C\"><\/span>What is &#8220;<em>this<\/em>&#8220;?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Now that you understand the &#8220;Execution Context,&#8221; you can now go to the next statement used to define the &#8220;this&#8221; keyword.<\/p>\n\n\n\n<p>&#8220;<em>this&#8221; refers to an object &#8211; that object that is currently executing your bit of Javascript code.<\/em>&#8220;<\/p>\n\n\n\n<p>In the Global Context Execution illustration above, &#8220;this&#8221; refers to the &#8220;global object,&#8221; which is the &#8220;browser window object.&#8221;<\/p>\n\n\n\n<p>With that information, you can now derive more definitions of the &#8220;this&#8221; keyword in Javascript.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>By default, the &#8220;this&#8221; keyword refers to the global object.<\/li><li>When used in a regular function (<em>not in strict mode<\/em>), &#8220;<em>this<\/em>&#8221; refers to the global object.<\/li><li>When used in a function with strict mode, &#8220;this&#8221; is undefined.<\/li><li>If a function is a method in an object, the &#8220;this&#8221; keyword will refer to the &#8216;object&#8217; itself.<\/li><li>In event handling, &#8220;this&#8221; refers to the element that receives the event.<\/li><li>In constructor functions, &#8220;this&#8221; is bound to the object created using the &#8220;new&#8221; keyword.<\/li><\/ul>\n\n\n\n<p class=\"has-vivid-green-cyan-background-color has-background\"><strong>Tip<\/strong>: A simple trick you can use to understand the &#8220;this&#8221; keyword easily is &#8211; all that matters is <em>how<\/em>, <em>when<\/em> and <em>from<\/em> where a function is called. Not <em>how<\/em> or <em>where<\/em> the function is declared or defined.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"%E2%80%9Cthis%E2%80%9D_in_the_Global_Context\"><\/span>&#8220;<em>this&#8221; <\/em>in the<em> <\/em>Global Context<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>When the &#8220;<em>this<\/em>&#8221; keyword is used outside a function or an object, &#8220;<em>this<\/em>&#8221; refers to the &#8216;global object. If on a browser, &#8220;this&#8221; will refer to the &#8220;window&#8221; object. Therefore, you can access methods and properties on that window object. These include &#8220;alert,&#8221; &#8220;setTimeout,&#8221; &#8220;scroll&#8221; etc.<\/p>\n\n\n\n<p>In the case of <a href=\"https:\/\/nodejs.org\/en\/about\/\" target=\"_blank\" rel=\"noopener\">NodeJS<\/a>, the global object is no longer the &#8220;browser window.&#8221; Instead, &#8220;this&#8221; will refer to a special object called &#8220;global.&#8221; Similar to the &#8220;window object&#8221;, the &#8220;global object&#8221; in NodeJS gives you access to various methods. They include &#8220;_dirname,&#8221; &#8220;_filename,&#8221; &#8220;process,&#8221; &#8220;setTimeout&#8221; and many more.<\/p>\n\n\n\n<p>Have a look at the code below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>let a = this\nconsole.log(a)\n\n\/*---Output---\nWindow&nbsp;{0: global, window: Window, self: Window, document: document, name: '', location: Location,&nbsp;\u2026}<\/code><\/pre>\n\n\n\n<p>After running the code above on a browser console, we got an output of the &#8220;<em>window object<\/em>.&#8221; That&#8217;s because our code is executed in the global context, and &#8216;this&#8217; refers to the &#8216;global object&#8217; &#8211; the &#8220;browser window&#8221; in this case.<\/p>\n\n\n\n<p>We can compare the &#8220;this&#8221; keyword and the &#8220;window&#8221; object and see whether we will get a boolean True or False.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>let a = this;\nconsole.log(a === window);\nconsole.log(a.document === document);\/\/Here, document is a value in the 'window object'\n\n\/*---Output---\ntrue\ntrue<\/code><\/pre>\n\n\n\n<p>We got an output of &#8220;true&#8221; for both. Let&#8217;s look at something much more interesting.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>this.a = \"Hey developer\";\nconsole.log(window.a)\n\n\/*---Output---\nHey developer<\/code><\/pre>\n\n\n\n<p class=\"language-javascript\">So, what is happening here? the first line adds an element to the &#8216;global object&#8217; using the statement <code>this.a = \"Hey developer\"<\/code>. Next, since &#8220;this&#8221; refers to the &#8220;window object,&#8221; you can access the newly added element using <code>window.a<\/code>. When you <code>console.log(this)<\/code> on the browser console, you can see the element that was added inside the &#8220;window object.&#8221;<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"350\" src=\"https:\/\/www.becomebetterprogrammer.com\/wp-content\/uploads\/2022\/08\/log-window-object-1024x350.png\" alt=\"\" class=\"wp-image-3428\" srcset=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/08\/log-window-object-1024x350.png 1024w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/08\/log-window-object-300x103.png 300w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/08\/log-window-object-1536x525.png 1536w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/08\/log-window-object-2048x700.png 2048w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption>log window object<\/figcaption><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"%E2%80%9Cthis%E2%80%9D_in_Function_Context\"><\/span>&#8220;<em>this<\/em>&#8221; in Function Context<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>When used on functions, the behavior of the &#8220;this&#8221; keyword depends on whether the function is using &#8220;<a href=\"https:\/\/www.educative.io\/answers\/what-is-strict-mode-in-javascript\" target=\"_blank\" rel=\"noopener\">strict mode<\/a>&#8221; or not.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"%E2%80%9Cthis%E2%80%9D_in_a_Function_without_strict_mode\"><\/span>&#8220;<em>this<\/em>&#8221; in a Function (without strict mode)<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"language-javascript\">When used in a regular function <strong>without strict mode<\/strong>, the &#8220;this&#8221; keyword will always refer to the global object, which is the &#8220;window object&#8221; in the case of browsers. The window object in this scenario is the owner of our function &#8211; <code>myFunc()<\/code>. <\/p>\n\n\n\n<p class=\"has-luminous-vivid-amber-background-color has-background\"><strong>Note<\/strong>: here, we are talking about a stand-alone function that is not affiliated with any object.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>function myFunc(){\n return this;\n}\nconsole.log(myFunc());\nmyFunc() === window;\n\n\/*---Output---\nWindow&nbsp;{0: global, window: Window, self: Window, document: document, name: '', location: Location,&nbsp;\u2026}\ntrue<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"%E2%80%9Cthis%E2%80%9D_in_a_Function_with_strict_mode\"><\/span>&#8220;<em>this<\/em>&#8221; in a Function (with strict mode)<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>When a function is <strong>used in strict mode<\/strong>, Javascript does not allow default binding. Therefore, the &#8220;this&#8221; keyword here is &#8220;undefined.&#8221; See the code snippet below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>function myFunc_2(){\n    \"use strict\"\n    return this;\n}\nconsole.log(myFunc_2());\nmyFunc_2 === window\n\n\/*---Output---\nUndefined\nfalse<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"%E2%80%9Cthis%E2%80%9D_in_Function_Method_Context\"><\/span>&#8220;<em>this<\/em>&#8221; in Function Method Context<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In Javascript, objects can consist of simple values or methods. When a function is used inside an &#8216;object,&#8217; we refer to it as a &#8220;method.&#8221; If &#8220;this&#8221; is used inside the method, whenever the method is invoked, &#8220;this&#8221; will refer to the object upon which the method was invoked. That object becomes the owner of the method.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>let fruits = {\n   mango:\"Yellow\",\n   lemon:\"Green\",\n   myFunc() {\n       console.log(`I Love ${this.mango}`)\n    }\n}\nfruits.myFunc()\n\n\/*---Output---\nI Love Yellow<\/code><\/pre>\n\n\n\n<p>Here, &#8220;this&#8221; refers to the &#8220;fruits&#8221; object. Let&#8217;s tweak the code and see the contents of &#8220;this&#8221; when the method is invoked.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>let fruits = {\n   mango:\"Yellow\",\n   lemon:\"Green\",\n   myFunc(){\n       console.log(this)\n    }\n}\nfruits.myFunc()\n\/*---Output---\n{ mango: 'yellow', lemon: 'green', myFunc: &#91;Function: myFunc] }<\/code><\/pre>\n\n\n\n<p class=\"language-javascript\">Quite interesting! From the output above, you can see that &#8220;this&#8221; refers to the &#8220;fruits&#8221; object upon which the method was invoked &#8211; <code>fruits.myFunc()<\/code>. Below is a more complex example of the<em> <\/em>&#8220;this&#8221; keyword when used with &#8220;methods.&#8221;<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>function greet(){\n   console.log(\"How are you \" + this.name)\n}\nconst person_1 = {\n    name:\"John Doe\",\n    greet\n}\nconst person_2 = {\n    name:\"Mike\",\n    greet\n}\nperson_1.greet()\nperson_2.greet()\n\n\/*---Output---\nHow are you John Doe\nHow are you Mike<\/code><\/pre>\n\n\n\n<p class=\"language-javascript\">Here, the two objects,<em> &#8220;<\/em>person_1 and person_2<em>,&#8221; <\/em>both borrow the &#8220;greet function<em>.&#8221; <\/em>In the case of <code>person_1.greet()<\/code>,<em> <\/em>the <em>&#8220;<\/em>this<em>&#8221; <\/em>keyword refers to the &#8220;person_1&#8221; object. In <code>person_2.greet()<\/code>, &#8220;this&#8221; refers to &#8220;person_2&#8221; object.<\/p>\n\n\n\n<p>You can verify that by tweaking the code above and seeing the output of &#8220;this&#8221; as shown below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>function greet(){\n   console.log(this)\n}\nconst person_1={\n    name:\"John Doe\",\n    greet\n}\nperson_1.greet()\n\n\/*---Output---\n{ name: 'John Doe', greet: &#91;Function: greet] }\n<\/code><\/pre>\n\n\n\n<p>From the output above, you can see that &#8220;this&#8221; is referencing the &#8220;person_1&#8221; object. <\/p>\n\n\n\n<p>This section has introduced us to re-usability using the &#8220;this&#8221; keyword. We have one function <code>greet()<\/code> that is used with two different objects (person_1 and person_2). From the two code snippets we have looked at, you can deduce that the &#8220;this&#8221; keyword in a function can have different meanings depending on who is calling it.<\/p>\n\n\n\n<p class=\"has-vivid-green-cyan-background-color has-background\"><strong>Tip<\/strong>: &#8220;<strong><em>Who is on the left side rule.<\/em><\/strong>&#8220;<br>That is another tip you can rely on when working with the &#8220;this&#8221; keyword. It states &#8211; The &#8220;<em>this<\/em>&#8221; keyword is the object on the left side of the function invocation. <\/p>\n\n\n\n<p>When you apply that rule to all the above examples up to this point; you will realize the rule applies. In the last code snippet, &#8220;person_2&#8221; is on the left side of the function invocation.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"%E2%80%9Cthis%E2%80%9D_in_Arrow_Functions\"><\/span>&#8220;<em>this<\/em>&#8221; in Arrow Functions<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Arrow functions were introduced in ES6. Unlike regular functions, arrow functions allow developers to write neat, easy-to-read code. When using &#8220;this&#8221; with arrow functions, the definitions we have looked at above don&#8217;t apply.<\/p>\n\n\n\n<p>That&#8217;s because Arrow functions don&#8217;t create an execution context. Therefore, they don&#8217;t have their own &#8220;this.&#8221; Instead, they inherit the &#8220;this&#8221; of the outer function where they are defined. Take a look at the code below to have a better understanding.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>let fruits = {\n  mango: 'Yellow Mangoes',\n  sayColor() {\n    mango: 'Green Mangoes';\n    let myFunction = () =&gt; console.log(`I Love ${this.mango}!`);\n    myFunction();\n  }\n};\nfruits.sayColor();\n\n\/*---Output---\nI Love Yellow Mangoes!\n<\/code><\/pre>\n\n\n\n<p>From the output above, you can see that the &#8220;this&#8221; keyword in arrow functions refers to the object that defined the arrow function. In this case, it&#8217;s the &#8216;fruits&#8217; object. <\/p>\n\n\n\n<p class=\"language-javascript\">If instead, you were to log &#8220;this&#8221; in the arrow function <code>let myFunction = () =&gt; console.log(this)<\/code>, you would get the result below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>{ mango: 'Yellow Mangoes', sayColor: &#91;Function: sayColor] }<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"%E2%80%9Cthis%E2%80%9D_With_the_Call_and_Apply_Methods\"><\/span>&#8220;<em>this<\/em>&#8221; With the Call and Apply Methods<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p class=\"language-javascript\">When a function uses the &#8220;this&#8221; keyword in its body, its value can be bound to a particular object when invoked by using the <code>call()<\/code> and <code>apply()<\/code> methods. Have a look at the code snippet below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>function add(num1, num2){\n    let c = this.a + this.b + num1 + num2;\n    console.log(c)\n}\nconst myObj = {a:7, b:9};\nadd.call(myObj,10, 12)\n\n\/*---Output---\n38<\/code><\/pre>\n\n\n\n<p class=\"language-javascript\">F focus on the <code>add.call(myObj,10, 12)<\/code> line. The first parameter of the call() method is the object the function will use as &#8220;this.&#8221; In this case, it&#8217;s<em> <\/em>the &#8216;myObj&#8217; object. The other arguments (10, 12) are passed to <code>add()<\/code> function as parameters &#8211; <em>num1<\/em> and <em>num2<\/em> respectively.<\/p>\n\n\n\n<p class=\"language-javascript\">The <code>apply()<\/code> method is similar to the <code>call()<\/code> method. The only difference is that <code>call()<\/code> method accepts an argument list while the <code>apply()<\/code> method accepts a single array of arguments. Replace the <code>call()<\/code> method above with <code>apply()<\/code> as shown below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>function add(num1, num2){\n    let c = this.a + this.b + num1 + num2;\n    console.log(c)\n}\nconst myObj = {a:7, b:9};\nadd.apply(myObj,&#91;12,15])\n\n\/*---Output---\n43<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"%E2%80%9Cthis%E2%80%9D_with_the_Bind_Method\"><\/span>&#8220;<em>this<\/em>&#8221; with the Bind() Method<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p class=\"language-javascript\">When you call the <code>bind()<\/code> method on a function and pass an object, it creates a new function with the same body scope as the original function. But where &#8220;this&#8221; occurs in the original function, in the new function, &#8220;this&#8221; is permanently bound to the first argument of the <code>bind()<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>function myFunc() {\n  return this.name;\n}\n\nvar greet = myFunc.bind({name: 'Hello John'});\nconsole.log(greet());\n\n\/*---Output---\nHello John<\/code><\/pre>\n\n\n\n<p class=\"language-javascript\">In the code above, &#8220;this&#8221; refers to the object <code>{name: 'Hello John'}<\/code>, which is the argument passed in the bind method. Look at a more complex illustration of the <code>bind()<\/code> method below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>function Fruit(var1, var2) {\n\tthis.fruitOne = var1;\n\tthis.fruitTwo = var2;\n\n\tthis.displayName = function() {\n\t\tconsole.log(`I Love: ${this.fruitOne} and ${this.fruitTwo}`);\n\t}\n}\n\nlet fruit_1 = new Fruit(\"Mangoes\", \"Melons\");\nfruit_1.displayName(); \/\/I Love: Mangoes and Melons\nlet fruit_2 = new Fruit(\"Apples\", \"Amanatsu\");\nfruit_2.displayName(); \/\/I Love: Apples and Amanatsu\n\nlet person2Display = fruit_1.displayName.bind(fruit_2)\nperson2Display(); \/\/I Love: Apples and Amanatsu\n\n\/*---Output---\nI Love: Mangoes and Melons\nI Love: Apples and Amanatsu\nI Love: Apples and Amanatsu\n<\/code><\/pre>\n\n\n\n<p class=\"language-javascript\">In the code above, the line <code>fruit_1.displayName.bind(fruit_2)<\/code> creates a new function with value of \u201cthis\u201d equals to &#8220;fruit_2&#8221; object.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"%E2%80%9Cthis%E2%80%9D_in_Callback_Functions_Problem\"><\/span>&#8220;<em>this<\/em>&#8221; in Callback Functions (Problem)<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Take a look at the code below where we are calling &#8220;this&#8221; in a <a href=\"https:\/\/www.becomebetterprogrammer.com\/javascript-callback-functions\/\">callback function<\/a>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const fruits = {\n    Orange: \"Yellow\",\n    sayColor: function () {\n        setTimeout(function() {\n            console.log(\"I Love Color \" + this.Orange)\n        }, 100)\n    }\n}\nconsole.log(fruits.sayColor())\n\/*---Output---\nundefined\nI Love Color undefined\n<\/code><\/pre>\n\n\n\n<p class=\"language-javascript\">From the output above, you can now see the inconsistency with the &#8220;this&#8221; keyword in Javascript and why it becomes confusing to most developers. &#8220;this&#8221; in the <code>setTimeout()<\/code> function is undefined. <\/p>\n\n\n\n<p>That goes against our definition where we said &#8211; &#8220;this&#8221; will refer to the object upon which the method was invoked. It also goes against the rule &#8220;<em>Who is on the left side<\/em>.&#8221; There are three main ways to fix that.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Explicitly setting &#8220;this.&#8221;<\/li><li>Using Arrow function<\/li><li>Using bind()<\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Solution_1_Explicitly_setting_%E2%80%9Cthis%E2%80%9C\"><\/span>Solution 1: Explicitly setting &#8220;<em>this.<\/em>&#8220;<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Before ES6 and Arrow functions, developers used a technique of storing a reference to &#8220;this&#8221; in a variable. Therefore, one could simply call the variable whenever they wanted to use &#8220;this&#8221; in their code.<\/p>\n\n\n\n<p class=\"language-javascript\">To apply this solution in the code above, you will need to create a variable called &#8220;self&#8221; in the <code>sayColor()<\/code> function and set it to &#8220;this.&#8221;<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const fruits = {\n    Orange: \"Yellow\",\n    sayColor: function () {\n        let self = this; \/\/Store a refernce to 'this' in a variable\n        setTimeout(function() {\n            console.log(\"I Love Color \" + self.Orange)\n        }, 100)\n    }\n}\nfruits.sayColor()\n\/*---Output---\nI Love Color Yellow\n<\/code><\/pre>\n\n\n\n<p class=\"language-javascript\">As you know, &#8220;this&#8221; refers to the object upon which the method was invoked. In the code above, we invoked the <code>sayColor()<\/code> function on the fruits object. Therefore, &#8220;this&#8221; will refer to the &#8220;fruits&#8221; object. But since &#8220;this&#8221; is not accessible in the callback function, we saved a reference to &#8220;this&#8221; in the &#8220;self&#8221; variable.<\/p>\n\n\n\n<p>We can now proceed to use &#8220;self&#8221; in our callback function or any other section of our code.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Solution_2_Using_Arrow_Functions\"><\/span>Solution 2: Using Arrow Functions<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>In the previous sections when looking atthe relation of &#8220;this&#8221; and Arrow functions, this post stated that &#8211; <em>arrow functions inherit the &#8220;this&#8221; of the outer function where they are defined<\/em>. Using that concept, you can quickly solve the problem present here. You will covert the callback function to use an arrow function syntax.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const fruits = {\n    Orange: \"Yellow\",\n    sayColor: function () {\n        setTimeout(()=&gt;console.log(\"I Love Color \" + this.Orange),100)\n    }\n}\nfruits.sayColor()\n\n\/*---Output---\nI Love Color Yellow\n<\/code><\/pre>\n\n\n\n<p>Pretty clean and straightforward. What exactly is happening here?<\/p>\n\n\n\n<p class=\"language-javascript\">The &#8220;this&#8221; in the <code>setTimeout()<\/code> arrow function refers to the object where the arrow function is defined. In this case, it&#8217;s the &#8220;fruits&#8221; object.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Solution_3_Using_the_Bind_Method\"><\/span>Solution 3: Using the Bind() Method<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"language-javascript\">Of the three solutions, <code>bind()<\/code> is the most technical of all. Earlier when working with the bind() method, this post stated that &#8211; &#8220;<em>When you call the <code>bind()<\/code> method on a function and pass an object, it creates a new function with the same body scope as the original function<\/em>.&#8221; <\/p>\n\n\n\n<p class=\"language-javascript\">In this scenario, the solution would be to bind the <code>setTimeout()<\/code> function to the &#8220;fruits&#8221; object by passing &#8220;this&#8221; as an argument in the <code>bind()<\/code> method.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const fruits = {\n    Orange: \"Yellow\",\n    sayColor: function () {\n        setTimeout(function() {\n            console.log(\"I Love Color \" + this.Orange)\n        }.bind(this), 100)\/\/Here, we are binding the setTimeout() function to the fruits object.\n    }\n}\nfruits.sayColor()\n\n\/*---Output---\nI Love Color Yellow\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"%E2%80%9Cthis%E2%80%9D_in_Constructor_Functions\"><\/span>&#8220;<em>this<\/em>&#8221; in Constructor Functions<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Calling a function with the &#8220;new&#8221; keyword turns the function into a constructor. Constructor functions automatically create a binding between the object being created using the &#8220;new&#8221; keyword and the &#8220;this&#8221; keyword on the inside of the function. Take a look at the code below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>function Fruit(a){\n    this.name = a;\n    this.sayFruit = function(){\n        console.log(this) \/\/Here, we want to see the value of \"this\"\n        console.log(`I Love ${this.name}`)\n    }\n}\nconst newFruit = new Fruit(\"Mangoes\"); \/\/Here, we create a binding between the newly created object \"newFruit\" and the \"this\" keyword.\nnewFruit.sayFruit()\n\n\/*---Output---\nFruit { name: 'Mangoes', sayFruit: &#91;Function] }\nI Love Mangoes\n<\/code><\/pre>\n\n\n\n<p>When you take a keen look at the code above, you will also notice that the &#8220;<em>who is on the left rule<\/em>&#8221; applies here.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"%E2%80%9Cthis%E2%80%9D_in_Event_Handlers\"><\/span>&#8220;<em>this<\/em>&#8221;&nbsp;in Event Handlers<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>When used in inline event handling, the &#8220;this&#8221; keyword refers to the DOM element that is receiving the event. Assume we want to create a button that, when clicked, its display property is set to &#8220;none.&#8221; How, would you go about it?<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>&lt;button onclick=\"this.style.display='none'\"&gt;\n  Button Me!\n&lt;\/button&gt;<\/code><\/pre>\n\n\n\n<p>In the above code snippet, &#8220;this&#8221; refers to the button element. <\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1400\" height=\"418\" src=\"https:\/\/www.becomebetterprogrammer.com\/wp-content\/uploads\/2022\/08\/bind-event-handling-4.gif\" alt=\"\" class=\"wp-image-3473\"\/><figcaption>&#8220;this&#8221; in event handling<\/figcaption><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"%E2%80%9Cthis%E2%80%9D_Keyword_Precedence\"><\/span>&#8220;<em>this<\/em>&#8221; Keyword&nbsp;Precedence<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>There are cases where it&#8217;s hard to determine which object &#8220;this&#8221; refers to, especially when an application has a lot of <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Learn\/JavaScript\/Asynchronous\/Introducing\" target=\"_blank\" rel=\"noopener\">asynchronous code<\/a>. To solve that, &#8220;this&#8221; follows an order of precedence, as shown in the table below.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Precedence<\/strong><\/td><td><strong>Object<\/strong><\/td><\/tr><tr><td>1<\/td><td>bind()<\/td><\/tr><tr><td>2<\/td><td>call() and apply()<\/td><\/tr><tr><td>3<\/td><td>object method<\/td><\/tr><tr><td>4<\/td><td>Global scope<\/td><\/tr><\/tbody><\/table><figcaption>&#8220;<em>this<\/em>&#8221; order of precedence<\/figcaption><\/figure>\n\n\n\n<ul class=\"wp-block-list\"><li>In a function, is &#8220;this&#8221; called using the bind() method?<\/li><li>In a function, is &#8220;this&#8221; called using the apply() method?<\/li><li>In a function, is &#8220;this&#8221; called using the call() method?<\/li><li>In a function, is &#8220;this&#8221; inside a function in an object (method)?<\/li><li>In a function, is &#8220;this&#8221; in the Global Scope?<\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Although the &#8220;<em>this<\/em>&#8221; keyword can be quite confusing, this post has given you enough tips and tricks to help you understand the concept better. Try out more examples other than only those provided in the code snippets in this post. That way, you will have a solid understanding of how the &#8220;this&#8221; keyword works.<\/p>\n\n\n\n<p><strong>Was this article helpful? Do you have any comments or suggestions?<\/strong><\/p>\n\n\n\n<p>Let us know by replying on Twitter of\u00a0<a href=\"https:\/\/twitter.com\/bbprogrammer\" target=\"_blank\" rel=\"noreferrer noopener\">Become A Better Programmer<\/a>\u00a0or to my\u00a0<a href=\"https:\/\/twitter.com\/tonygidraph\" target=\"_blank\" rel=\"noreferrer noopener\">personal Twitter account<\/a>.<\/p>\n\n\n\n<figure class=\"wp-block-embed aligncenter is-type-rich is-provider-twitter wp-block-embed-twitter\"><div class=\"wp-block-embed__wrapper\">\n<blockquote class=\"twitter-tweet\" data-width=\"550\" data-dnt=\"true\"><p lang=\"en\" dir=\"ltr\">In <a href=\"https:\/\/twitter.com\/hashtag\/javascript?src=hash&amp;ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"noopener\">#javascript<\/a> , &quot;this&quot; keyword is not what you think.<br><br>With a few tips and tricks, you can become better at identifying what the value of &quot;this&quot; is depending on the context.<a href=\"https:\/\/twitter.com\/TonyGidraph?ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"noopener\">@TonyGidraph<\/a> shares with us a complete guide to understanding &quot;this&quot; keyword.<a href=\"https:\/\/t.co\/P3TiYi5XCc\">https:\/\/t.co\/P3TiYi5XCc<\/a><\/p>&mdash; Become A Better Programmer (@bbprogrammer) <a href=\"https:\/\/twitter.com\/bbprogrammer\/status\/1556979304944345088?ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"noopener\">August 9, 2022<\/a><\/blockquote><script async src=\"https:\/\/platform.twitter.com\/widgets.js\" charset=\"utf-8\"><\/script>\n<\/div><\/figure>\n","protected":false},"excerpt":{"rendered":"<p>Javascript is becoming more popular for building web applications and mobile apps using React Native framework. Therefore, understanding its key concepts can come in quite handy. The &#8220;this&#8221; keyword in Javascript is a source of confusion and misery for most beginner Javascript developers and even pro-developers. This post aims to give you a beginner-friendly comprehensive &#8230; <a title=\"JavaScript | Complete Guide to Understanding &#8220;This&#8221; Keyword\" class=\"read-more\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-this-keyword\/\" aria-label=\"More on JavaScript | Complete Guide to Understanding &#8220;This&#8221; Keyword\">Read more<\/a><\/p>\n","protected":false},"author":8,"featured_media":3498,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"nf_dc_page":"","_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[16],"tags":[],"class_list":["post-3410","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-javascript","generate-columns","tablet-grid-50","mobile-grid-100","grid-parent","grid-50"],"_links":{"self":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/3410","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/users\/8"}],"replies":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/comments?post=3410"}],"version-history":[{"count":5,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/3410\/revisions"}],"predecessor-version":[{"id":3560,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/3410\/revisions\/3560"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media\/3498"}],"wp:attachment":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media?parent=3410"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/categories?post=3410"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/tags?post=3410"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}