This is Javascript

Danilo Peña
4 min readJun 2, 2022
Photo by George Lebada: https://www.pexels.com/photo/red-chameleon-567540/

In this article, we are gonna talk about the this keyword. What is this? How does this work? and why this is it not so hard?

this is a keyword in Javascript and it refers to different data depending on how you use this ( this is going to be funny 😅)

First of all, if you currently call this in the global scope of your object (and if you don’t know what a global scope is: this), this will refer you to the global object.

In case you console.log the this keyword in a JS code that’ll be executed in a browser, the global object will be Window.

This is the window object printed in the console of our browser’s dev tools

Alright, this is good!

Now, if we console.log this inside of a function… What will happen?

Same as with our global this , a this invoked inside of a function statement will refer to the global object.

But, what about functions declared as methods inside of an object?

First, bear in mind that in Javascript all objects inherit properties from other objects and functions are first-class objects, which basically means that functions are objects too (callable objects). So, when this is called inside of an object method it is referring to the object itself. And at that point, our object only has one element: the getUserName() method.

If we add more attributes to our user object and call again our getUserName method, this is what our console will print:

So, this is still basically referring to our object. And now that we have more properties, let’s give getUserName a more conscious meaning:

**Special Note: When executing JS code in strict mode. If you use this inside of a function, it’ll be undefined.

this inside of Event Handlers

For this example we have a button element:

If we assign a function to an event listener and call this inside of that function, our chameleonic keyword will refer us to the element that is receiving the event, in this case, the HTMLButtonElement :

using the this keyword inside of a function event handler will refer to the element’s event

Bear in mind that when using methods like bind() , this will refer to any object, which means that with Function.prototype.bind() we can provide a new value to be set to the this keyword… But there will be another occasion for getting our hands dirty with this … or maybe that!

Conclusion

The this keyword is very powerful if we do know how this works! Remember that everything in Javascript is an object! so for understand which objects this refers to, we should ask ourselves:

  1. Is this called from bind(), apply() or call(), or…
  2. Is this called inside a function statement?
  3. Is this called in a method?
  4. Is this called globally?

Thanks and don’t forget to read about this :

  1. Javascript This (w3schools)
  2. This operator (MDN)

Thanks for reading this! Cheers!

--

--