Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] JavaScript this Keyword

#1
JavaScript this Keyword

<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2022/09/javascript-this-keyword.jpg" width="550" height="413" title="" alt="" /></div><div><div class="modified-on" readability="7.1666666666667"> by <a href="https://phppot.com/about/">Vincy</a>. Last modified on September 13th, 2022.</div>
<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>
<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>
<ul>
<li>Global context</li>
<li>Method context</li>
<li>function context</li>
<li>Class context</li>
<li>Event context</li>
</ul>
<p>In these contexts JavaScript <em>this</em> keyword refers to the different objects correspondingly.</p>
<p>The below code uses the ‘this’ 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>
<div class="post-section-highlight" readability="38">
<h2>Quick Example</h2>
<p class="code-heading">This example uses ‘JavaScript this’ in the object’s method to read properties.</p>
<pre class="prettyprint"><code class="language-javascript">
&lt;script&gt;
const category = { mainCategory: "Gadgets", subCategory: "Mobile phones", DisplayCategoryTree : function() { return this.mainCategory + " -&gt; " + this.subCategory; }
};
document.write(category.DisplayCategoryTree());
&lt;/script&gt;
</code></pre>
</div>
<p><img 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/20...00x225.jpg 300w, https://phppot.com/wp-content/uploads/20...68x576.jpg 768w, https://phppot.com/wp-content/uploads/20...t-this.jpg 960w" sizes="(max-width: 550px) 100vw, 550px"></p>
<h2>How it works</h2>
<p>The behavior of using ‘this’ varies based on several factors. Some of them are listed below.</p>
<ol>
<li>It differs between dynamic and explicit binding.</li>
<li>It works differently on strict and non-strict modes.</li>
<li>It varies based on the enclosing contexts.</li>
<li>It differs based on how and where they are called or used.</li>
</ol>
<p>Generally, the ‘this’ will behave with dynamic binding. JavaScript supports explicit binding with the bind() method to change the default.</p>
<p>Without default value, the JavaScript ‘this’ returns ‘undefined’ in a strict mode.</p>
<h2>Different usages of ‘this’ in JavaScript</h2>
<p>There are different usage practices in JavaScript to use the <a href="https://phppot.com/php/php-self-vs-this/">‘this’ keyword</a> to refer to a context. Let us see about the following 2 among those practices.</p>
<ol>
<li>Set default values to the ‘this’.</li>
<li>Arrow function.</li>
</ol>
<p>By default, the ‘this’ refers to the global context. But, in strict mode, functions need a default value to use ‘this’ as a reference. The JavaScript classes are always in a strict mode and require object reference to use ‘this’.</p>
<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>
<h2>More examples using JavaScript this</h2>
<p>This section gives more examples of the ‘JavaScript this’ keyword. It shows how ‘this’ will work in different scenarios and contexts.</p>
<p>It gives code for accessing properties of a class or JavaScript const block.</p>
<p>It accesses the HTML elements on event handling. It helps to manipulate the DOM objects via JavaScript with the reference of the ‘this’ keyword.</p>
<h3>Example 1: Accessing object properties via <em>this</em> using JavaScript call() function</h3>
<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 ‘<em>this’</em> object.</p>
<p class="code-heading">bind-objects-and-get-properties-with-this.html</p>
<pre class="prettyprint"><code class="language-javascript">
&lt;script&gt;
const category = { DisplayCategoryTree : function() { return this.mainCategory + " -&gt; " + this.subCategory; }
};
const categoryData = { mainCategory: "Gadgets", subCategory: "Mobile phones",
}; console.log(category.DisplayCategoryTree.call(categoryData));
&lt;/script&gt;
</code></pre>
<h3>Example 2: JavaScript <em>this</em> in Strict mode</h3>
<p>In strict mode, JavaScript this keyword refers to the global window context. But, within a function, it returns <em>undefined.</em></p>
<p class="code-heading">javascript-this-in-strict-mode.html</p>
<pre class="prettyprint"><code class="language-javascript">
&lt;script&gt; "use strict";
let obj = this;
// 'this' is 'window' object
console.log(obj); function getContext() { return this;
}
// In strict mode, JavaScript 'this' inside a funtion is 'undefined'
console.log(getContext());
&lt;/script&gt;
</code></pre>
<h3>Example 3: Set or get object properties using this keyword</h3>
<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>
<p class="code-heading">javascript-getter-setter-with-this-object-html.php</p>
<pre class="prettyprint"><code class="language-javascript">
&lt;script&gt;
const 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; }
};
Properties.setColor("White");
Properties.setSize("small");
Properties.setType("3D"); document.write("Color: "+ Properties.getColor()+"&lt;br&gt;");
document.write("Size: "+ Properties.getSize()+"&lt;br&gt;");
document.write("Type: "+ Properties.getType());
&lt;/script&gt;
</code></pre>
<h3>Example 4: JavaScript this object in different contexts</h3>
<p>This script logs the ‘JavaScript this’ object in different contexts. The program creates two classes and logs the ‘this’ object from their constructors. It returns the corresponding owner instance and logs it into the developer console.</p>
<p>I have written a similar tutorial on <a href="https://phppot.com/php/php-constructors-destructors/">PHP constructors and destructors</a> earlier.</p>
<p>From a jQuery document.ready() function, ‘this’ returns <em>Document:[object HTMLDocument]</em>.</p>
<p class="code-heading">this-in-different-context.php</p>
<pre class="prettyprint"><code class="language-html">
&lt;script src="https://code.jquery.com/jquery-3.6.0.min.js"&gt;&lt;/script&gt;
&lt;script&gt;
var x = this;
console.log("Default:" + x); class Cart { constructor() { console.log("Class:" + this + " of " + this.constructor.name); }
}
const cart = new Cart(); class Product { constructor() { console.log("Class:" + this + " of " + this.constructor.name); }
}
const product = new Product(); $(document).ready(function(){ var x = this; console.log("Document:" + x);
});
&lt;/script&gt;
</code></pre>
<p>This program logs the following in the developer console. The ‘this’ object refers to a different context.</p>
<p><img 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>
<h3>Example 5: JavaScript this keyword in event context</h3>
<p>The below code contains HTML button with an on-click event handler. It passes the ‘this’ object to manipulate the button element style. Here, the JavaScript this object refers to the button element.</p>
<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>
<p class="code-heading">this-in-event-handler.html</p>
<pre class="prettyprint"><code class="language-html">
&lt;button onclick="highlight(this)"&gt;Button&lt;/button&gt;
&lt;script&gt;
function highlight(obj) { obj.style.backgroundColor = '#0099FF';
}
&lt;/script&gt;
</code></pre>
<h3>Example 6: Using the Arrow function</h3>
<p>See the below example that creates a compact code to get a global context using ‘this’.</p>
<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 ‘this’.</p>
<p class="code-heading">arrow-function.html</p>
<pre class="prettyprint"><code class="language-html">
&lt;script&gt;
var getGlobal = (() =&gt; this);
console.log(getGlobal());
&lt;/script&gt;
</code></pre>
<h2>Conclusion</h2>
<p>I hope you have a good idea of this basic JavaScript concept. The example code guides you on how to use ‘this’ in JavaScript.</p>
<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>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
</p></div>
<p> <a href="https://phppot.com/javascript/javascript-this/#top" class="top">↑ Back to Top</a> </p>
</div>


https://www.sickgaming.net/blog/2022/09/...s-keyword/
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016