Simplifying THIS key word specifically for Javascript .

Hallo Readers!

Today the topic would be one of the corner stone of JavaScript programming. Usage of this key word!

In my experience I have noticed that there are two kind of Java Script developers. One those who prefer to use JavaScript only for web tweeks, even though this number is decreasing fast, still this group is not doing enough to embrace the new functionalities. These are the people generally hate THIS! The other set of people who believes JavaScript is as good as other programming language like C++ , C# , Java and they try to blend in their knowledge of OOPs programming to Javascript. These are the people who loves THIS!

Either you love or hate THIS, THIS does not care! Being one of those people who never dipped his toe much in the Java Scripts, I used to HATE THIS! In a quick soul searching I found the reason, which is I was not too sure or confident to use THIS in my daily programming. Below is a snapshot of how I preferred to code:

With out THIS:

Now clearly, this code is very clear and simple.  If you have noticed, the “this” in the previous sentence takes you to the example above. As in the context of things there is no other thing it can potentially refer to. In the world of programming it behaves the exact same way. If THIS is being used with in a context like with in a method then its referring to the Object that is holding the method. If its being used in a global scope then its referring to the global objects. Now this gets tricky these days, as global objects are different! For a web based platform, global object is window object where as for node based system the global object is globalThis. Now, as you have noticed I used the word Object in previous sentences, that is quite misleading as there are no class concept inside JS (the Class keyword is inherently a method), so the better wording would be closures / scope. So, THIS refers to the  parent scope it belongs!

The same example with THIS:

As you can see the code is so much cleaner and your method gets so much room to accommodate business required parameter than things you needed for plumbing. Also, there are plenty of other use cases that you can leverage, however those are kept aside for another session!



Till then let me know how you likes THIS topic and if you have any questions. Below are the links that explains THIS concept to my satisfaction!


Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top