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"

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

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.

Join the newsletter!

Front end dev doesn't have to be hard! Tips and articles to help you become a better front-end dev.

    We won't send you spam. Unsubscribe at any time.