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 hascolor
property with a value ofred
printColor
method that is referring thecolor
property withthis
. This will simply do a console log of thecolor
.
Now remember that
printColor()
method is usingthis
inside its function scope.First, I called the method on
holi
object, i.e.holi.printColor()
What is left to
printColor()
method =>holi
object.So, when javascript gets to the line where
this.color
is, it will use thecolor
property on theholi
object
Secondly, I am making one const
proxyPrintColor
(you can also call itprintColor
). This is referring theprintColor
method insideholi
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.