Understanding this in JavaScript: A Beginner's Guide

Sangwin Gawande
3 min readNov 1, 2024
Understanding this in JavaScript: A Beginner’s Guide
Understanding this in JavaScript: A Beginner's Guide

JavaScript is a powerful and versatile programming language, but one of the trickiest concepts to grasp is the keyword this. Its behavior can change based on how and where it is used. As someone who has navigated the early stages of learning JavaScript, I remember the confusion and frustration I faced when trying to understand this. In this blog, I’ll break down how this works in different contexts: regular functions, classes, and arrow functions, along with a personal experience that helped me make sense of it all.

1. `this` in Regular Functions

In regular functions, the value of this can vary depending on how you call the function.

Global Context

If you call a function in the global scope (not attached to any object), this refers to the global object. In a browser, this is usually window.

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

showThis(); // Outputs: Window (or global object in Node.js)

Object Method

When a function is called as a method of an object, this refers to that object.

const obj = {
name: 'Alice',
greet: function() {
console.log(this.name);
}
};

obj.greet(); // Outputs: Alice

Constructor Function

If you call a function with the new keyword, this refers to the newly created object.

function Person(name) {
this.name = name;
}

const person = new Person('Bob');
console.log(person.name); // Outputs: Bob

2. this in Classes

In ES6 classes, this behaves similarly to regular functions. Inside a class method, this refers to the instance of the class.

class Animal {
constructor(name) {
this.name = name;
}

speak() {
console.log(this.name + ' makes a noise.');
}
}

const dog = new Animal('Dog');
dog.speak(); // Outputs: Dog makes a noise.

However, be careful when passing class methods as callbacks. If a class method is used as a standalone function, this may not refer to the instance anymore.

const speak = dog.speak;
speak(); // Outputs: undefined (or throws an error in strict mode)

To fix this, you can use .bind(), or use an arrow function.

3. this in Arrow Functions

Arrow functions are a newer way to write functions in JavaScript. One of their key features is that they do not have their own this. Instead, they inherit this from the surrounding scope where they are defined. This makes them very useful for preserving this in callbacks.

const obj = {
name: 'Charlie',
greet: function() {
setTimeout(() => {
console.log(this.name); // 'this' refers to obj
}, 1000);
}
};

obj.greet(); // After 1 second: Outputs: Charlie

If you used a regular function inside setTimeout, this would not refer to obj.

const obj2 = {
name: 'Daisy',
greet: function() {
setTimeout(function() {
console.log(this.name); // 'this' is undefined or window
}, 1000);
}
};

obj2.greet(); // After 1 second: Outputs: undefined

A Personal Experience

I remember one night, sitting at my desk, wrestling with a project for a coding bootcamp. I had a function that was supposed to greet users based on their name, but for some reason, it was logging undefined. After hours of debugging, I realized I was using a regular function inside a callback. That’s when it clicked for me: the context of this was changing based on how I called the function.

That experience taught me not just about this, but also about the importance of understanding context in JavaScript. It felt like a light bulb moment, and from then on, I approached functions with a new mindset.

Summary

  • Regular Functions: The value of this depends on how the function is called. It can refer to the global object, an object, or a newly created instance.
  • Classes: Inside class methods, this refers to the instance of the class. Be cautious with how you pass methods as callbacks.
  • Arrow Functions: this is lexically inherited, meaning it keeps the value of this from its surrounding scope, which helps avoid issues in callbacks.

Understanding how this works in different contexts is essential for mastering JavaScript and writing clean, effective code. By keeping these concepts in mind, you'll be better equipped to handle the challenges that arise when working with JavaScript.

I hope my journey resonates with you, and helps you in your own coding adventures.

Happy coding!

Cheers!!

Sangwin Gawande

About me : https://sangw.in

--

--

No responses yet