Simplifying Javascript: the “this” keyword
Written by — Rajashree Parhi| Edited by — Arka Sengupta
Building stuff has never been easier! With a plethora of tutorials and resources available on the internet, it’s fair to say that we will soon have private spaceships that’ll take us to the moon.
Jokes aside, diving down the tutorial hole might seem counter-intuitive but, is never the ideal way to learn stuff. You can watch 100 JS tutorials, but you won’t know a damn thing if you don’t know the language fundamentals.
In short, you need me. That’s why I’ve planned to write on the seemingly complex concepts of the almighty Javascript and turn them into simple nuggets of info so that you can SUPERCHARGE and BUIDL!
Oh! and… never forget to thank me. (By hitting the follow button)
What is “this”?
Much like in the case of the English Language, where this is used in reference to its immediate surroundings, Javascript follows the same principles.
Example — If you’re inside the four walls of our house and you state:
This furniture needs to be repaired!
It typically means that you are referring to a piece of furniture that is inside your house. In essence, this here refers to your house’s furniture.
But, if you repeat the same sentence inside a furniture shop,
This now refers to the furniture inside the shop and not of your home.
Connecting it back to JS, the word “this” is used to refer to the object or the function inside which you have used the word.
Syntax example
‘this’ in global scope
If used in the global context, this refers to the global object i.e the ‘window’.
Let’s look at another example,
Here, window sofa and sofa both are available on a global scope.
But, these become the public property of windows that can be accessed from outside.
This brings me to my next point, What if I want to limit the furniture to my room only?
‘this’ inside an object
myHome is a private variable and it’s not accessible on “this”. Instead, I have to call in the following way-
‘this’ inside a function
myHome.print()-> denotes the method of myHome object
this.showroom.print()-> denotes the method of showroom object.
What if I want to print on the global scope? Let’s see what happens now.
Since I am executing it without strict mode, it prints the data. But what if I am using strict mode?
However, in strict mode, inside the function, ‘this’ is not set. Hence, it stays undefined. The reason being print() is called directly and not as a method or property of an object as shown in other examples.
Closing thoughts
Mystery Box: How do I use print() for this.furniture then?
Get the comments going, with your answers. I will reveal how to do it, next time.