DEV Community

Cover image for Explaining JavaScript 'this' to my cat
Andrey K.
Andrey K.

Posted on • Updated on

 

Explaining JavaScript 'this' to my cat

My cat is not very good at JavaScript (also at many other things), so today I will try to explain this keyword to him to help in his future career.


The main rule is: you don't need to remember this as long as console.log(this) exists. So you can go back to your sleep, cat. But, if cat's curiosity got better of you, you may read a bit more.


The first thing you need to know: in functions, this refers to a thing, or a calamity which executed the function. For functions described with a function keyword we are summoning a massive Global Object which executes the function in our name. For our browser, this object is called Window, so this refers to it. We can pretend we're executing the function this way:

function petTheCat() {
  console.log('Purring...');
  console.log(this); // Window
}
window.petTheCat(); // equals to petTheCat();
Enter fullscreen mode Exit fullscreen mode

However, in strict mode ("use strict";) in this case this will remain undefined 😿

The same logic applies to objects. When calling an object method, we bow the object to our will, forcing it to do the execution. So, this refers to the object itself. In these examples we can say that this is what's on the left side of the dot symbol.

const catObject = {
  takeThis() {
    return this; // { catObject }
  }
}
catObject.takeThis();
Enter fullscreen mode Exit fullscreen mode

One of the cases where this doesn't behave is using bind(), call() and apply() methods. Those three were specifically cast by JavaScript blacksmiths for this. They are designed to point at something to execute a function on (create a new function in case of bind()), this is their first argument, and it can be literally anything, even this itself 😨

cat.call(this, name);
feedCat.bind(myCat, 'no-arguments');
Enter fullscreen mode Exit fullscreen mode

Another curious case would be using an event listener. In this case a browser decides what's best for us by referring this to the target of an event (for example, to a button which we clicked).

cat.addEventListener('pet', purrFunction);
function purrFunction() {
  console.log('Purring...');
  console.log(this); // cat
}
Enter fullscreen mode Exit fullscreen mode

At last, when we create a brand new object using a constructor or constructor function (with a new keyword), this inside the constructor would refer to a shiny new object we're creating.

class SuperCat {
  constructor(superPower) {
    this.superPower = superPower;
  }
}
Enter fullscreen mode Exit fullscreen mode

The last important thing to know is using this with arrow functions. And the best thing is that arrow functions couldn't care less about this! Practically, it means they are totally ignoring it (and maybe hoping this will go away), so the context of this right outside the arrow function stays the same inside it. This behavior can be useful with constructors and event listeners, for example.

class SuperCat {
  constructor(name, belly) {
    this.name = name;
    this.belly = belly;
  }
  superMethod() {
    // Without '=>' this would refer to the belly
    this.belly.addEventListener('pet', () => this.purrFunction());
  purrFunction() {
    console.log('Purring...');
    // Now it refers to the new object
    this.name = 'Purring ' + this.name;
  }
}
Enter fullscreen mode Exit fullscreen mode

And that's it for my cat (who's sleeping loudly).
Thank you for reading, sorry for being completely unprofessional!


Links

this (MDN)
Function.prototype.call() (MDN)
Function.prototype.apply() (MDN)
Function.prototype.bind() (MDN)
constructor (MDN)
new operator (MDN)

Top comments (4)

Collapse
 
mohsenalyafei profile image
Mohsen Alyafei

Excellent. Thanks.

Collapse
 
viniciusrio profile image
Vinicius Rio

If I understood ... The cat understood too

Collapse
 
jmr_code_social profile image
Jorge Marquez

Thanks, for this!

Collapse
 
bogdaaamn profile image
Bogdan Covrig

can we make this ELIC a thing?

cats hacking through life

Visualizing Promises and Async/Await 🤯

async await

☝️ Check out this all-time classic DEV post