The JavaScript "this" keyword

The JavaScript "this" keyword

·

7 min read

Hello friend,

How are you doing today? Together, we will talk about the JavaScript this keyword, so be sure to open up your code editor and run each code snippet as you read along!..Cheers!!..lol

Even though it is widely used by developers, JavaScript this is still one of the most confusing keyword in Javascript.

In this article, we will look at the different values the object this can take up when a code is executed, but before we dive into that, we need a little understanding of the JavaScript run time environment and how JavaScript code is executed.

Global Execution Context

Before your code runs (even if your file is empty), the JavaScript engine creates something called the global execution context. The global execution context is the environment (or scope) in which your line of code is being executed and it has two phases – the creation phase and the execution phase.

In the creation phase of the global execution context, memory is allocated to your function, a scope chain is created, the global object and the this keyword also gets created automatically(when a function is invoked).

The execution phase basically means the execution of your code. The JavaScript runtime maintains a stack of these execution contexts, and executes them starting from the one currently at the top of the stack. The this keyword refers to changes made each time the execution context changes. Now, let's take a dive into the this keyword proper.

How does JavaScript 'this' keyword work?

The this keyword is a pointer which refers to the object it belongs to. In other words, it references the object that is executing the current function. JavaScript this keyword has different values depending on how the code is being executed. When dealing with a regular function, this by default references the window object in browsers and the global object in a nodeJs environment.

this - In the Global Scope

When this is used alone in the global scope, it refers to the window object in the browser or the global object in NodeJs as in the code below;

 console.log(this); 

// Refers to the window object

Same thing also applies when it is used in a regular function as seen below;

function sayHi() {
    console.log(this);
}
sayHi();  

//Refers to the window object

this - Inside Object's method

If a function is part of an object, it is called a method. When this is used in a method, it points to the object containing the method and not the window object this time.

// this when used in a method

const obj = {
    name: "kisha",
    hobby: "reading",
    sayHi : function () {
        console.log(this);
    }
};

obj.sayHi();  // {name: "kisha", hobby: "reading", sayHi: ƒ}

Javascript can be tricky sometimes especially with the this keyword, so avoid using arrow functions when declaring a method. It's best to use arrow functions when declaring a function inside a method in an object.

In other words;

// DON'T DO THIS

const obj = {
    name: "kisha",
    hobby: "reading",
    sayHi: () => {
        console.log(this);
    }
};

obj.sayHi();   // Refers to window object

/* Declaring a method with arrow function
 refers to the window object and not 
 the current object containing the method*/

this - In a Function(Strict)

JavaScript strict mode does not allow default binding. So in a strict mode, this is undefined. In the code below, adding a strict mode - "use strict" will return undefined when you run the code on your console.

function sayHi() {
  "use strict";
  console.log(this);
}
sayHi();  // undefined

The bind, call and apply method

Functions are special objects in JavaScript. Every function has a bind, call and apply method, and these methods can be used to assign a value to this in the execution phase of the function.

this - with the bind Method

The bind method allows you to call a method inside a function. It can be used to set the this keyword to a specified object when a function is invoked. Take a look at the code below;

const user = {
      firstName: "Code with",
      lastName: "kisha",
      fullName: function(){
          console.log(this.firstName + " " + this.lastName);
      }
  };

 function getAllNames(){
     console.log(this);
 }

getAllNames(); 

// Window {parent: Window, opener: null, top: Window, length: 0, frames: Window, …}

In the code above, this refers to the window object by default because we invoked the function getAllNames and not the method fullName. However, we can make the keyword this refer to the specific object we want.

In these case, we want this to refer to the object user. To do this we save the getAllNames to a variable and add the method bind to the getAllNames function as seen below and viola!! we have our this referencing the object user.

const user = {
      firstName: "Code with",
      lastName: "kisha",
      fullName: function(){
          console.log(this.firstName + " " + this.lastName);
      }
  };

 function getAllNames(){
     console.log(this);
 }

 const register = getAllNames.bind(user);

 register();

// {firstName: "Code with", lastName: "kisha", fullName: ƒ}

Try replacing console.log(this) with this.fullName() in your code editor and see what you get - remember, you learn fast by doing ;)

this - with the call and apply Method

Ok! moving on, with call() and apply() method, we are actually not saving the function to a variable, rather we're invoking the function directly by adding a parameter to the function name and passing in an argument. Here is an example of how the call method works;

const user = {
      firstName: "Code with",
      lastName: "kisha",
      fullName: function(){
          console.log(this.firstName + " " + this.lastName);
      }
  };

 function getAllNames(gender, profession){
     console.log(`Hey there!! I am a ${gender} and I love ${profession}`);
 }

getAllNames.call(user, "girl", "tech");
// Hey there!! I am a girl and I love tech

Just so you know, there is no much difference between call() and apply(). The only difference is that with apply() you can pass in an array as an argument like this;

 const user = {
    firstName: "Code with",
    lastName: "kisha",
    fullName: function(){
        console.log(this.firstName + " " + this.lastName);
    }
};

function getAllNames(gender, profession){
   console.log(`Hey there!! I am a ${gender} and I love ${profession}`);
}

getAllNames.apply(user, ["girl", "tech"]);

// Hey there!! I am a girl and I love tech

There's so much you can do with JavaScript this, but at this point I'm going to call it wrap. I really hope that this article was able to explain how javascript this keyword works. Thank you for taking your time to read through.

Did I mention that this is my first published article?? Yeah, it actually is.. lol.. If you found this article helpful, kindly give it a like...I would also appreciate any feedback on how to improve my writing as I would love to write more...Cheers!!