"THIS" keyword in javascript made simple for you

ยท

5 min read

"THIS" keyword in javascript made simple for you

In this blog, i will try to simplify "this" keyword for you, after functional components you might think the importance of "this" keyword is reduced but not my friend, through "this" is not REACT SPECIFIC feature it sure is Essential javascript concept on which you must have mastery. So let's start....

UNDERSTANDING THE CONTEXT

"This is my car" sounds perfect in two situations only, when you are inside the car or you are in front of the car. The other person will automatically understand where your "THIS" points to as he understands the context. Now imagine you are in middle of dinner and you shout "This is my car". Nobody will get what you are trying to say, as they don't understand the context. So context is the circumstances which gives meaning to your absurd statements*.* Similarly in javascript depending upon the context where "this" keyword is used we can understand where it points.

In Global Context

Even when we don't write any line of code in our JS file, some things are created in the background, one of this is WINDOW object, which gives us access to various features and method. If you don't know Window object, then it is a global object which gets created by javascript even when haven't wrote anything.

In global context, "this" refers to this window object, so when we use this outside of any function in global space we get a what ? YESS, A window object. ๐ŸŽ‰

Inside a function

// Non strict Mode

function Function1 () {
   console.log(this) //Window Object
}

Function();

In Non-strict mode when when we use "this" keyword in a function it simply points to OWNER of that function which in this case is global object ie. Window object

// Non Strict Mode
function Function1 () {
   return this
}

function1() === window // TRUE

In the example above, the value of the this keyword as used inside this function refers to the window object. This is why the output of the string comparison between funtion1 and the window object will equal to true because they hold the exact same value.

// Strict Mode

function Function1 () {
   console.log(this) // Undefined
}

Function();

In strict mode however, "this" keyword returns UNDEFINED

Now you will wonder why this difference ?? ๐Ÿค”

Its pretty easy to understand, Think why would a developer access window object inside a function ?, Generally we use this to access properties of a function so in strict mode Javascript doesn't allow any sloppy code.

Inside an object

this.name = "Toyota"
const Printcarname = {
  name : "Audi"
  mycar : function () {
      console.log(this.name)
  }
}

Printcarname.mycar() // Output = Audi

We have an object Printcarname and a method inside this object called mycar, when we write "this" inside an object, it points to the object itself in which the method is defined, since mycar method is in Printcarname object, [This.name] will mean the name property of this object.

Here is a catch

this.name = "Toyota"
const Printcarname = {
  name : "Audi"
  mycar : function () {
      console.log(this.name)
  }
}

const globalvehicle = Printcarname.mycar

globalvehicle() //Output = Toyota

Now what if we assign our method mycar to another variable and call that variable ? What it will print ?

In this case it will print the global output because we are no longer calling the method of object inside it but we are assigning that method to a global variable and thus this function is an independent function now which means it represents the global object.

Inside an event handler

First of all let's understand what is an event ?

An event is the occurrence of something that we consider important. Example -singing event, or dance event.

Similarly in javascript, An event handler is an action carried out when an event is perceived to have happened. we developers read this event and decide what actions we have to take on the completion of a particular event. For example we might decide to change the background color on a button click.

So we need something to check if event occurred and initiate an action after event completion, that thing is EVENT HANDLERS

window.addEventListener("keydown", function (event) {

In the example above, an event listener of keydown is being listened for by the window object, and once that event is perceived, a function that takes in the event will be run. The job of that function is to console.log this.event.key. If you try to run this code on the browser, you will get back whichever key the user pressed. Hence, in this case, this refers to the window object which is the one receiving the object, and as with all other objects, its properties can be accessed using the dot(.) operator. The value of this when used in an event handler will refer to the receiver of the event, which can be the window object in this case or any other local HTML elements we might create.

You can still explore "this" keyword in javascript and its scope of work expands way than what blog has taken, but in the end, after reading this blog, you will have good understanding of what "THIS" is, what "Context" is, How if differs in Strict and Non strict mode and basics of event handler.

I hope you liked this blog, if yes, then appreciate it by sharing it with your friends.

THANK YOU !!!

ย