DEV Community

Cover image for // Let's learn `this` in Javascript
Miguel Ben
Miguel Ben

Posted on

// Let's learn `this` in Javascript

Hello World,

Today we will be going over the javascript keyword this (clickable). The value of this refers to the object that is executing at the current function (runtime binding). This topic often confuses a plethora of developers because it's one of the most commons JS keywords, but it's hard to tell what does this means.

I'm assuming that you already know what an object, and a method is. However, if you are feeling rusty let's do a quick recap:

  • What is an object?

is a set of data stored in name-value pairs (Hashes or key-value pairs).

Example of an obj: 👇

const person = {
    name: "Greg",
    power_level: 10000,
    hobby: "cycling",
    age: "unknown",
    skill_user: true

In an obj you are able to store values such as string, integers, booleans, functions and even other objects.

  • What is a method?

is a function that belongs to an object.

const person = {
    word: 'Alright!~',

    shouting: function(){
        console.log('Hey Luke!! wink wink ~');

person.shouting(); // => Hey Luke!! wink wink ~

In the prior example shouting is a method of our person object.

Qué es esto / this? 🧐

Again, in the context of JS 'this' refers to the object that our function belongs to. An example of this could be our person obj inside a function:

Example 1:

const person = {
  name: "Isaac",
  routine: function() {
    console.log(this); // `this` refers to the current instance | object called person

person.routine(); // => { name: 'Isaac', routine: [Function: routine] }

Executing the code above will let us see the person object.

  > typeof person
  > 'object'

Example 2:

const person = {
    power_level: 25,

    afterTraining: function(){ // camel case
        this.power_level += 300;

console.log('initial power level of ' + person.power_level + ".");
// => initial power level of 25.

person.afterTraining(); // => +300

console.log('Power after training: ' + person.power_level+ ".");
// => Power after training: 325.

As we can see the afterTraining function increases the power_level by 300.


Hey bud! are you still w/ me?

Global context

If we type this in our browser console, it will refer to window - global object. Chrome: Press ⌘ + ⇧ + C to access the browser console.

this // => Window obj

let hello = 'Hello, World!'
this.hello // => Hello, World!

window.heyCarl = 'Hey, Carl.'
this.heyCarl // => Hey, Carl.

const helloFix = 'Hello...repairman'
this.helloFix // => und ... undefined?

Recap: 🔍

  • By default this gets set to "window" obj, unless declared as something else.
  • this is the obj that our function belongs to when called.

Thanks for reading 👋. Hey check out one of my friends blog:

Shoutout Round 1


Anything else?

Did I miss something? Please let me know in the comments!



By the way this was my first post! 🎉🎉🎉

Top comments (0)