Small trick to understand the `this` keyword
Nico Zerpa (he/him)

Nico Zerpa (he/him) @nicozerpa

About: Your JavaScript friend! I've been working for over a decade in JS, and I want to help you level up your skills

Location:
Buenos Aires, Argentina
Joined:
Mar 7, 2021

Small trick to understand the `this` keyword

Publish Date: Feb 13 '23
0 0

The this keyword is one of the biggest headaches for anyone learning JavaScript. In this article, I won't go too deep into how the keyword works, but I will give you a quick tip to make it easier to handle.

As a general rule, the this keyword represents what's left of the dot when you're calling the method. Let's see an example:

class Capybara {
    constructor(name) {
        this.name = name;
    }
    sayName() {
        return `My name is ${this.name}`;
    }
}

const capyDavid = new Capybara("David");
const capyArianna = new Capybara("Arianna");

capyDavid.sayName();
// ☝️ "this" is `capyDavid`,
//    returns "My name is David"

capyArianna.sayName();
// ☝️ "this" is `capyArianna`,
//   returns "My name is Arianna"

Enter fullscreen mode Exit fullscreen mode

In JavaScript, functions are values. That is, you can pass functions as arguments, or assign them to variables. But when you do it, things get tricky:

const sayDavidName = capyDavid.sayName;
sayDavidName();
// ☝️ It fails! There's nothing "left of the dot"
//   because there's no dot.

function quoteCapybara(sayNameFuntion) {
    return `A capybara says: "${sayNameFuntion()}"`;
}
quoteCapybara(capyArianna.sayName);
// ☝️ It fails too
Enter fullscreen mode Exit fullscreen mode

In the last example (the quoteCapybara function), why does it fail when you correctly passed the function as capyArianna.sayName? Because the function is executed inside the quoteCapybara function. There, it's run as sayNameFunction, so there's nothing "left of the dot".

In those cases, the most recommended solution is to change quoteCapybara so that it receives the capybara object as the parameter.


Become a Better JavaScript Developer
Easy, actionable steps to level up your JavaScript skills, right to your inbox. Click here to subscribe

Comments 0 total

    Add comment