One Simple explanation of `this` inside JavaScript

  • Even the most experienced developers sometimes make mistakes while using this in JavaScript or TypeScript ( I am learning Typescript now... LOL)

  • In simple terms, this is going to be equal to the left of the function call.

const holi = {
  color: "red",
  printColor() {
    console.log(this.color);
  }
};

holi.printColor(); // red

const proxyPrintColor = holi.printColor;
proxyPrintColor(); // undefined: Cannot read properties of undefined (reading 'color')
  • Above I have an object holi. It has

    • color property with a value of red

    • printColor method that is referring the color property with this. This will simply do a console log of the color.

  • Now remember that printColor() method is using this inside its function scope.

  • First, I called the method on holiobject, i.e. holi.printColor()

    • What is left to printColor() method => holiobject.

    • So, when javascript gets to the line where this.color is, it will use the color property on the holiobject

  • Secondly, I am making one const proxyPrintColor (you can also call it printColor ). This is referring the printColor method inside holi object. It is not calling the function, just referencing it.

    • What is left to proxyPrintColor method => nothing.

    • That is why color is undefined in this case. So this condition will result in an error.