<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by faaat on Medium]]></title>
        <description><![CDATA[Stories by faaat on Medium]]></description>
        <link>https://medium.com/@faaat?source=rss-8b5b3d419420------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by faaat on Medium</title>
            <link>https://medium.com/@faaat?source=rss-8b5b3d419420------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 08:39:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@faaat/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[This keyword in JavaScript]]></title>
            <link>https://medium.com/@faaat/this-keyword-in-javascript-88f7de9a14f1?source=rss-8b5b3d419420------2</link>
            <guid isPermaLink="false">https://medium.com/p/88f7de9a14f1</guid>
            <dc:creator><![CDATA[faaat]]></dc:creator>
            <pubDate>Tue, 05 Dec 2023 14:11:05 GMT</pubDate>
            <atom:updated>2023-12-25T13:02:03.940Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bt0ur84joqyXk1x7S6hRxQ.jpeg" /></figure><p>In this article, we’re going to find out what is this(!) in JavaScript and review its value in different situations. In the following, firstly we want to learn its definition in general and then find which situations can change its value.</p><p>OK, firstly let’s look over the definition:</p><p>In JavaScript, the this keyword refers to an object that is executing the current function. The objects it refers to are different depending on how it is used, such as the below table:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fsheetsu.com%2Ftables%2F98e354a9f3&amp;dntp=1&amp;display_name=Sheetsu&amp;url=https%3A%2F%2Fsheetsu.com%2Ftables%2F98e354a9f3&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=sheetsu" width="700" height="532" frameborder="0" scrolling="no"><a href="https://medium.com/media/6be2c03972bfe2d1b5d81bcfa20a66f3/href">https://medium.com/media/6be2c03972bfe2d1b5d81bcfa20a66f3/href</a></iframe><p>OK! Let’s see some detailed examples in practice :</p><ul><li>In an object literal this refers to the global object (window).</li></ul><pre>const foo = {<br>  a: this,  // refers to window<br>};</pre><ul><li>As you see below, in an object method the this keyword refers to the object that owns the method.</li></ul><pre>const foo = {<br>  title: &quot;a&quot;,<br>  b() {<br>    console.log(this); // refers to foo obj<br>  }<br>};<br><br>foo.c = function () {<br>  console.log(this); // refers to foo obj<br>};</pre><ul><li>What about a function? Generally in a function with normal call, this refers to window. But based on the function type and how the function is called, it may differ.</li></ul><pre>function foo() {<br>  console.log(this); // refers to window<br>}<br><br>foo();</pre><ul><li>this keyword refers to the receiver of the event when it’s used in an event.</li></ul><pre>&lt;button onclick=&quot;this.style.display=&#39;none&#39;&quot;&gt;<br>  Click to Remove Me!<br>&lt;/button&gt;<br><br>// refers to button element</pre><p>If you’re a Js developer, you must know that in some specific situations the value of this would change! So you should be aware of its value in these specific conditions to change it if needed. Let’s see what conditions you may face:</p><h3>Strict Mode</h3><p>Strict mode makes several changes to normal JavaScript semantics as mentioned below:</p><ol><li>It would change this keyword behavior.</li><li>Eliminates some JavaScript silent errors by altering them to throw errors.</li><li>Fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that’s not strict mode.</li><li>Prohibits some syntax likely to be defined in future versions of ECMAScript.</li></ol><h4>this reference in strict mode</h4><pre>&quot;use strict&quot;;<br><br>function foo() {<br>  console.log(this); // undefined<br>}<br><br>foo();</pre><h3>new operator</h3><p>We have different ways to define object in Js:</p><p>1. Object Literal</p><pre>const person = {<br>  name: &#39;John Doe&#39;,<br>  age: 30,<br>  address: &#39;123 Main Street&#39;<br>};</pre><p>2. Factory Function</p><pre>function creatCircle(radius) {<br>  return {<br>    radius,<br>    draw() {<br>      console.log(&quot;draw&quot;);<br>    }<br>  };<br>}<br><br>const circle1 = creatCircle(1);<br>circle1.draw(); // draw</pre><p>A factory function can be defined as a function that creates an object and returns it. It is similar to constructor functions/class functions.</p><p>If a function returns a new object without the new keyword, they are said to be a Factory Function. The Naming Convention used here is the camel Notation.</p><p>3. Constructor Function</p><p>Constructor Functions are used to construct or create an object. It is another pattern for creating objects just like the Factory Functions. It differs from the Factory Function in its use case and naming convention. The naming convention used in Constructor Function is the Pascal Notation</p><pre>const circleObj = function Circle(radius) {<br>  this.radius=radius,<br>  this.draw = function (){<br>    console.log(this)<br>  }<br>}<br><br>const circle = new Circle(1);<br>circle.draw() // refers to circleObj<br><br>// we get refrence from draw method and do not call it<br>const draw = circle.draw<br>draw() // refers to window</pre><p>When we use new operator, 4 things happen:</p><ol><li>It creates a new, empty object; something like const x ={};</li><li>It binds this to our newly created object.</li><li>It adds a property onto our newly created object called “__<strong>proto__</strong>” which points to the constructor function’s prototype object.</li><li>It adds a return this to the end of the function, so that the object that is created is returned from the function.</li></ol><h3>Callbacks</h3><p>When you pass a function as a callback, the value of this may differ depending on how the callback is called, which is determined by the implementer of the API. Callbacks are typically called with a this value of undefined (calling it directly without attaching it to any object), which means if the function is non–strict, the value of this is the global object. This is the case for iterative array methods, the Promise() constructor, etc.</p><p>Time to see an example:</p><pre>const foo= {<br>  title: &quot;a&quot;,<br>  tags: [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;],<br>  showTags() {<br>    this.tags.forEach(function (tag) {<br>      console.log(this.title, tag);<br>    });<br>  }<br>};<br><br>obj.showTags();<br>// this.title =&gt; undefined<br>// this refers to window</pre><p>Here, we have foo object, which has some properties (title &amp; tags) and a method named showTags. Inside the showTags we used the forEachcallback.</p><p>Our goal is that forEach callback, iterates on tags property and logs the title property per each element. But we saw that in the console the value of the title was undefined.Why does this happen?</p><p>The reason is that the forEach callback here is a regular function that the window object executes. In simple words, if this comes inside the forEach callback which is used in such a situation, it refers to global object (window).</p><p>Now the question is <strong><em>“How can we change the value of </em></strong><strong><em>this in callbacks?”</em></strong></p><h3>Changing value of this in callbacks</h3><p>To do so, we have different ways that we mentioned below:</p><p>1. Optional ‍‍‍‍‍this parameter in some callbacks</p><p>Some APIs allow you to set a this value for invocations of the callback. For example, all iterative array methods and related ones like set.prototype.forEach() accept an optional this parameter.</p><pre>[1, 2, 3].forEach(<br>  function () {<br>    console.log(this);<br>  },<br>  { name: &quot;obj&quot; }<br>);<br><br>// { name: &#39;obj&#39; }, { name: &#39;obj&#39; }, { name: &#39;obj&#39; }</pre><p>Let’s get back to the last example we had:</p><pre>const foo= {<br>  title: &quot;a&quot;,<br>  tags: [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;],<br>  showTags() {<br>    this.tags.forEach(function (tag) {<br>      console.log(this.title, tag);<br>    },this); // we passed this as forEach optional ‍parameter<br>  }<br>};<br><br>obj.showTags();<br>// this.title =&gt; &quot;a&quot;<br>// this refers to foo</pre><p>Now by this solution, this refers to the foo object because it is outside of the callback and is inside of the showTags method.</p><p>But all methods in Js don’t have that option! What else do we have?</p><p>2. Pass value of this through callback parameter</p><pre>const foo= {<br>  title: &quot;a&quot;,<br>  tags: [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;],<br>  showTags() {<br>    const that = this;<br><br>    this.tags.forEach(function (tag) {<br>      console.log(that.title, tag); //using &#39;that&#39; variable instead of &#39;this&#39;<br>    });<br>  }<br>};<br><br>obj.showTags();<br>// that.title =&gt; &quot;a&quot;<br>// this refers to foo</pre><p>3. Using call(), apply(), bind() methods to call function</p><pre>function foo(a, b) {<br>  console.log(this);<br>}<br><br>foo(1, 2);  // window<br>foo.call({ name: &quot;a&quot; }, 1, 2);  // refers to { name: &quot;a&quot; }<br>foo.apply({ name: &quot;a&quot; }, [1, 2]);  // refers to { name: &quot;a&quot; }<br>foo.bind({ name: &quot;a&quot; });  // refers to { name: &quot;a&quot; }</pre><p>All three of these functions helps you change the context of the invoking function. We use them to set the this keyword independent of how the function is called.</p><p>Difference between call and apply and bind is that bind doesn’t call the function, it returns a new function and sets this to point to the desired object.</p><pre>const fn = function.bind({});<br>fn();<br><br>//or<br>function.bind({})()</pre><p>Difference between call and apply is in passing arguments; arguments in apply method pass through an array.</p><p>In our example:</p><pre>const foo= {<br>  title: &quot;a&quot;,<br>  tags: [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;],<br>  showTags() {<br>    this.tags.forEach(function (tag) {<br>      console.log(this.title, tag);<br>    }.bind(this));<br>  }<br>};<br><br>obj.showTags();<br>// this.title =&gt; &quot;a&quot;<br>// this refers to foo</pre><p>4. Arrow functions</p><p>A good thing about arrow functions is that they inherit the this value.</p><p>In arrow functions, this retains the value of the enclosing lexical context this. In other words, when evaluating an arrow function’s body, the language does not create a new this binding.</p><p>Arrow functions create a closure over the this value of its surrounding scope, which means arrow functions behave as if they are “auto-bound” — no matter how it’s invoked, this is set to what it was when the function was created. The same applies to arrow functions created inside other functions: their this remains in that enclosing lexical context.</p><pre>const foo = () =&gt; this;<br>const obj = { name: &quot;obj&quot; };<br><br>// refers to window, not obj<br>foo.call(obj)<br>foo.bind(obj)</pre><p>In our example:</p><pre>const foo= {<br>  title: &quot;a&quot;,<br>  tags: [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;],<br>  showTags() {<br>    this.tags.forEach(tag =&gt; console.log(this.title, tag)); //using arrow function syntax instead of regular function<br>  }<br>};<br><br>obj.showTags();<br>// this.title =&gt; &quot;a&quot;<br>// this refers to foo</pre><h3>Conclusion</h3><p>We reviewed the definition of this keyword and its value in general mode such as object literal, object methods, functions and events. We learned how this value might change in different situations and how to change it by ourselves with examples.</p><p>Hope you find it insightful. Good coding!</p><h3>References</h3><ol><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88f7de9a14f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>