DEV Community

Cover image for Understanding this in JavaScript: Guide for Beginners
Chidera Humphrey
Chidera Humphrey

Posted on

Understanding this in JavaScript: Guide for Beginners

Introduction

The this keyword is one of the most confusing concepts in JavaScript. Many developers struggle with the concept of this.

However, understanding the concept of this is crucial for learning object-oriented programming (OOP) in JavaScript.

In this article, I will explain what the concept of this is and how it is used in different contexts.

What is this?

In simple terms, this refers to an object. this makes it convenient to reference objects. Without this, referencing an object would be difficult as you'll need to write more code. This can make your code error-prone.

The object this refers to, depends on the context in which this was called.

Let's look at the different contexts this can be called in JavaScript:

Object method

When used in an object method, this refers to the object that bears the method.

const person = {
  name: "John Doe",
  greet() {
    console.log(`Hello, my name is ${this.name}`);
  },
};

person.greet(); // Hello, my name is John Doe
Enter fullscreen mode Exit fullscreen mode

In the code above, this refers to the person object.

Constructors

In constructor functions, this refers to the new object instance created by the constructor function.

class Toyota {
  constructor(model) {
    this.model = model;
  }
}

const toyota = new Toyota("Camry");

console.log(toyota.model); // Camry
Enter fullscreen mode Exit fullscreen mode

In the code above, this refers to the toyota instance.

Functions

In a function, the this keyword refers to the object calling the function.

If the function is called in the global scope, this refers to the global object.

function greet() {
  console.log(this); // window object
}

greet();
Enter fullscreen mode Exit fullscreen mode

In the above code, this refers to the window object.

Note: In the browser, the global object refers to the window object. In Node.js, the global object refers to the global object.

If the function is an object method, this refers to the calling object.

const person = {
  name: "John Doe",
  greet() {
    console.log(this); // person object
  },
};

person.greet();
Enter fullscreen mode Exit fullscreen mode

In the code above, this refers to the person object.

In strict mode, this returns undefined.

"use strict";

function greet() {
  console.log(this); // undefined
}

greet();
Enter fullscreen mode Exit fullscreen mode

Arrow functions

Arrow functions, introduced in ES6, are a more concise way of declaring functions. Arrow functions provide a more shorter syntax for declaring functions.

// Traditional function
function greet() {
  console.log(this);
}

// Arrow function
const greet = () => {
  console.log(this);
};
Enter fullscreen mode Exit fullscreen mode

Unlike in regular functions, this works differently in arrow functions.

In an arrow function, this refers to the owner of the function—context/scope where the arrow function was declared. This is because in arrow functions, there's no binding of this.

In the code below, the arrow function is declared in the global context/scope, and so this refers to the global object, window, in this case.

const greet = () => {
  console.log(this);
};

greet(); // window object
Enter fullscreen mode Exit fullscreen mode

If you try to attach the function to an event handler, the greet() function will still refer to the window object. See below.

<button>Click Me</button>
<p id="paragraph"></p>
Enter fullscreen mode Exit fullscreen mode
const button = document.querySelector("button");

const greet = () => {
    document.getElementById("paragraph").innerText += this;
};

button.addEventListener("click", greet);
Enter fullscreen mode Exit fullscreen mode

 raw `this` endraw  refers to  raw `window` endraw  object

Event handlers

Event handlers are functions that handle HTML events. HTML events are actions carried out by the browser or user. HTML events include but are not limited to the following:

  • Page load
  • Button click
  • Page scroll

In event handlers, this refers to the object receiving the event.

For example, in this code, this refers to the HTML button element, since it's the object receiving the onclick event:

<button onclick="greet()">Click me!</button>
<p id="paragraph"></p>
Enter fullscreen mode Exit fullscreen mode
function greet() {
  document.getElementById('paragraph').innerText += this; // button element
}
Enter fullscreen mode Exit fullscreen mode

 raw `this` endraw  refers to HTML element

Explicit binding

You can explicitly specify the object you want this to refer to. JavaScript provides three built-in methods (call(), apply(), bind()) that help you specify the object you want this to refer to.

call() and apply()

These two methods allow you to borrow a method from another object.

const person1 = {
    name: "John Doe",
    greet: function (){
        console.log(`Hello, I'm ${this.name}`);
    }
}

const person2 = {
    name: "Susan Doe"
}

// using call()
person1.greet.call(person2); //Hello, I'm Susan Doe

// using apply()
person1.greet.apply(person2); //Hello, I'm Susan Doe
Enter fullscreen mode Exit fullscreen mode

The call() and apply() methods are identical in functionality. The only difference between the two is that call() accepts a list of arguments while apply() accepts an array of arguments.

bind()

The bind() method works pretty much the same way as call() and apply() methods. The difference is that the bind() method returns a function while call() and apply() returns the result of calling the function.

const person1 = {
    name: "John Doe",
    greet: function (){
        console.log(`Hello, I'm ${this.name}`);
    }
}

const person2 = {
    name: "Susan Doe"
}

const greetPerson2 = person1.greet.bind(person2);

greetPerson2(); // Hello, I'm Susan Doe
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this article, you have learned about the this keyword in JavaScript. You have seen how this can be used in different contexts, such as object methods, constructors, functions, and event handlers. You have also seen how this works differently in arrow functions.

The this keyword is a powerful tool in JavaScript, but it can also be confusing. I hope this article has helped you to better understand how this works and how to use it effectively in your code.

If you have any questions or feedback about this article, please feel free to leave a comment below.

You can also connect with me on LinkedIn and X (formerly Twitter)

Additional resources

FAQs

Can I change the value of this?

No. this is a keyword and like any other keyword, you can't change the value of this. Rather, you can use bind(), call(), or apply() to explicitly specify the object this references.

Can I use this in strict mode?

It is not recommended. Using this in strict mode returns undefined, which can lead to bugs in your code.

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.