{"id":128081,"date":"2022-09-13T06:13:49","date_gmt":"2022-09-13T06:13:49","guid":{"rendered":"https:\/\/phppot.com\/?p=15692"},"modified":"2022-09-13T06:13:49","modified_gmt":"2022-09-13T06:13:49","slug":"javascript-this-keyword","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2022\/09\/13\/javascript-this-keyword\/","title":{"rendered":"JavaScript this Keyword"},"content":{"rendered":"<div class=\"modified-on\" readability=\"7.1666666666667\"> by <a href=\"https:\/\/phppot.com\/about\/\">Vincy<\/a>. Last modified on September 13th, 2022.<\/div>\n<p>JavaScript <strong>this<\/strong> keyword is for referring to objects of the current context. If no context around, it points to the window context by default.<\/p>\n<p>There is more context the JavaScript can refer to via <em>this<\/em> keyword<em>.<\/em> The below list shows some of them.<\/p>\n<ul>\n<li>Global context<\/li>\n<li>Method context<\/li>\n<li>function context<\/li>\n<li>Class context<\/li>\n<li>Event context<\/li>\n<\/ul>\n<p>In these contexts JavaScript <em>this<\/em> keyword refers to the different objects correspondingly.<\/p>\n<p>The below code uses the \u2018this\u2019 keyword to print the <a href=\"https:\/\/phppot.com\/wordpress\/create-wordpress-plugin-to-show-post-taxonomy-breadcrumbs\/\">main and sub-category breadcrumb<\/a> in the browser.<\/p>\n<div class=\"post-section-highlight\" readability=\"38\">\n<h2>Quick Example<\/h2>\n<p class=\"code-heading\">This example uses \u2018JavaScript this\u2019 in the object\u2019s method to read properties.<\/p>\n<pre class=\"prettyprint\"><code class=\"language-javascript\">\n&lt;script&gt;\nconst category = { mainCategory: \"Gadgets\", subCategory: \"Mobile phones\", DisplayCategoryTree : function() { return this.mainCategory + \" -&gt; \" + this.subCategory; }\n};\ndocument.write(category.DisplayCategoryTree());\n&lt;\/script&gt;\n<\/code><\/pre>\n<\/div>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-large wp-image-15986\" src=\"https:\/\/phppot.com\/wp-content\/uploads\/2021\/10\/javascript-this-550x413.jpg\" alt=\"javascript this\" width=\"550\" height=\"413\" srcset=\"https:\/\/phppot.com\/wp-content\/uploads\/2021\/10\/javascript-this-550x413.jpg 550w, https:\/\/phppot.com\/wp-content\/uploads\/2021\/10\/javascript-this-300x225.jpg 300w, https:\/\/phppot.com\/wp-content\/uploads\/2021\/10\/javascript-this-768x576.jpg 768w, https:\/\/phppot.com\/wp-content\/uploads\/2021\/10\/javascript-this.jpg 960w\" sizes=\"auto, (max-width: 550px) 100vw, 550px\"><\/p>\n<h2>How it works<\/h2>\n<p>The behavior of using \u2018this\u2019 varies based on several factors. Some of them are listed below.<\/p>\n<ol>\n<li>It differs between dynamic and explicit binding.<\/li>\n<li>It works differently on strict and non-strict modes.<\/li>\n<li>It varies based on the enclosing contexts.<\/li>\n<li>It differs based on how and where they are called or used.<\/li>\n<\/ol>\n<p>Generally, the \u2018this\u2019 will behave with dynamic binding. JavaScript supports explicit binding with the bind() method to change the default.<\/p>\n<p>Without default value, the JavaScript \u2018this\u2019 returns \u2018undefined\u2019 in a strict mode.<\/p>\n<h2>Different usages of \u2018this\u2019 in JavaScript<\/h2>\n<p>There are different usage practices in JavaScript to use the <a href=\"https:\/\/phppot.com\/php\/php-self-vs-this\/\">\u2018this\u2019 keyword<\/a> to refer to a context. Let us see about the following 2 among those practices.<\/p>\n<ol>\n<li>Set default values to the \u2018this\u2019.<\/li>\n<li>Arrow function.<\/li>\n<\/ol>\n<p>By default, the \u2018this\u2019 refers to the global context. But, in strict mode, functions need a default value to use \u2018this\u2019 as a reference. The JavaScript classes are always in a strict mode and require object reference to use \u2018this\u2019.<\/p>\n<p>The JavaScript arrow functions give compact code. So we can choose it for writing a limited code with purposes. But, I prefer to use traditional expressions while coding.<\/p>\n<h2>More examples using JavaScript this<\/h2>\n<p>This section gives more examples of the \u2018JavaScript this\u2019 keyword. It shows how \u2018this\u2019 will work in different scenarios and contexts.<\/p>\n<p>It gives code for accessing properties of a class or JavaScript const block.<\/p>\n<p>It accesses the HTML elements on event handling. It helps to manipulate the DOM objects via JavaScript with the reference of the \u2018this\u2019 keyword.<\/p>\n<h3>Example 1: Accessing object properties via <em>this<\/em> using JavaScript call() function<\/h3>\n<p>This program binds the properties of an object with the method of another object. It uses the JavaScript call() to log the properties with the reference of the \u2018<em>this\u2019<\/em> object.<\/p>\n<p class=\"code-heading\">bind-objects-and-get-properties-with-this.html<\/p>\n<pre class=\"prettyprint\"><code class=\"language-javascript\">\n&lt;script&gt;\nconst category = { DisplayCategoryTree : function() { return this.mainCategory + \" -&gt; \" + this.subCategory; }\n};\nconst categoryData = { mainCategory: \"Gadgets\", subCategory: \"Mobile phones\",\n}; console.log(category.DisplayCategoryTree.call(categoryData));\n&lt;\/script&gt;\n<\/code><\/pre>\n<h3>Example 2: JavaScript <em>this<\/em> in Strict mode<\/h3>\n<p>In strict mode, JavaScript this keyword refers to the global window context. But, within a function, it returns <em>undefined.<\/em><\/p>\n<p class=\"code-heading\">javascript-this-in-strict-mode.html<\/p>\n<pre class=\"prettyprint\"><code class=\"language-javascript\">\n&lt;script&gt; \"use strict\";\nlet obj = this;\n\/\/ 'this' is 'window' object\nconsole.log(obj); function getContext() { return this;\n}\n\/\/ In strict mode, JavaScript 'this' inside a funtion is 'undefined'\nconsole.log(getContext());\n&lt;\/script&gt;\n<\/code><\/pre>\n<h3>Example 3: Set or get object properties using this keyword<\/h3>\n<p>This example sets the properties of an object. Also. it reads them using the JavaScript this keyword. It defines functions to get or set the properties.<\/p>\n<p class=\"code-heading\">javascript-getter-setter-with-this-object-html.php<\/p>\n<pre class=\"prettyprint\"><code class=\"language-javascript\">\n&lt;script&gt;\nconst Properties = { color: \"Black\", size: \"Big\", type: \"2D\", getColor: function() { return this.color; }, setColor: function(newColor) { this.color = newColor; }, getSize: function() { return this.size; }, setSize: function(newSize) { this.size = newSize; }, getType: function() { return this.type; }, setType: function(newType) { this.type = newType; }\n};\nProperties.setColor(\"White\");\nProperties.setSize(\"small\");\nProperties.setType(\"3D\"); document.write(\"Color: \"+ Properties.getColor()+\"&lt;br&gt;\");\ndocument.write(\"Size: \"+ Properties.getSize()+\"&lt;br&gt;\");\ndocument.write(\"Type: \"+ Properties.getType());\n&lt;\/script&gt;\n<\/code><\/pre>\n<h3>Example 4: JavaScript this object in different contexts<\/h3>\n<p>This script logs the \u2018JavaScript this\u2019 object in different contexts. The program creates two classes and logs the \u2018this\u2019 object from their constructors. It returns the corresponding owner instance and logs it into the developer console.<\/p>\n<p>I have written a similar tutorial on <a href=\"https:\/\/phppot.com\/php\/php-constructors-destructors\/\">PHP constructors and destructors<\/a> earlier.<\/p>\n<p>From a jQuery document.ready() function, \u2018this\u2019 returns <em>Document:[object HTMLDocument]<\/em>.<\/p>\n<p class=\"code-heading\">this-in-different-context.php<\/p>\n<pre class=\"prettyprint\"><code class=\"language-html\">\n&lt;script src=\"https:\/\/code.jquery.com\/jquery-3.6.0.min.js\"&gt;&lt;\/script&gt;\n&lt;script&gt;\nvar x = this;\nconsole.log(\"Default:\" + x); class Cart { constructor() { console.log(\"Class:\" + this + \" of \" + this.constructor.name); }\n}\nconst cart = new Cart(); class Product { constructor() { console.log(\"Class:\" + this + \" of \" + this.constructor.name); }\n}\nconst product = new Product(); $(document).ready(function(){ var x = this; console.log(\"Document:\" + x);\n});\n&lt;\/script&gt;\n<\/code><\/pre>\n<p>This program logs the following in the developer console. The \u2018this\u2019 object refers to a different context.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-15974\" src=\"https:\/\/phppot.com\/wp-content\/uploads\/2021\/10\/javascript-this-reference.jpg\" alt=\"javascript this reference\" width=\"300\" height=\"94\"><\/p>\n<h3>Example 5: JavaScript this keyword in event context<\/h3>\n<p>The below code contains HTML button with an on-click event handler. It passes the \u2018this\u2019 object to manipulate the button element style. Here, the JavaScript this object refers to the button element.<\/p>\n<p>The on-click event calls the highlight(this) method. It will <a href=\"https:\/\/phppot.com\/jquery\/changing-div-background-using-bootstrap-colorpicker\/\">change the button background color<\/a> on click.<\/p>\n<p class=\"code-heading\">this-in-event-handler.html<\/p>\n<pre class=\"prettyprint\"><code class=\"language-html\">\n&lt;button onclick=\"highlight(this)\"&gt;Button&lt;\/button&gt;\n&lt;script&gt;\nfunction highlight(obj) { obj.style.backgroundColor = '#0099FF';\n}\n&lt;\/script&gt;\n<\/code><\/pre>\n<h3>Example 6: Using the Arrow function<\/h3>\n<p>See the below example that creates a compact code to get a global context using \u2018this\u2019.<\/p>\n<p>It creates a function consisting of a one-line code to return the global object. This line uses the JavaScript arrow function to use \u2018this\u2019.<\/p>\n<p class=\"code-heading\">arrow-function.html<\/p>\n<pre class=\"prettyprint\"><code class=\"language-html\">\n&lt;script&gt;\nvar getGlobal = (() =&gt; this);\nconsole.log(getGlobal());\n&lt;\/script&gt;\n<\/code><\/pre>\n<h2>Conclusion<\/h2>\n<p>I hope you have a good idea of this basic JavaScript concept. The example code guides you on how to use \u2018this\u2019 in JavaScript.<\/p>\n<p>The examples with event handlers and arrow functions return relevant object references. Let me know your valuable feedback on this article in the comment section.<br \/><a class=\"download\" href=\"https:\/\/phppot.com\/downloads\/javascript-this.zip\">Download<\/a><\/p>\n<p> <!-- #comments --> <\/p>\n<div class=\"related-articles\">\n<h2>Popular Articles<\/h2>\n<\/p><\/div>\n<p> <a href=\"https:\/\/phppot.com\/javascript\/javascript-this\/#top\" class=\"top\">\u2191 Back to Top<\/a> <\/p>\n","protected":false},"excerpt":{"rendered":"<p>by Vincy. Last modified on September 13th, 2022. JavaScript this keyword is for referring to objects of the current context. If no context around, it points to the window context by default. There is more context the JavaScript can refer to via this keyword. The below list shows some of them. Global context Method context [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":128082,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[65],"tags":[],"class_list":["post-128081","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-php-updates"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/128081","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=128081"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/128081\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media\/128082"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=128081"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=128081"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=128081"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}