Search This Blog

Sunday, 20 December 2015

Decoding "this" in the Javascript World

 A lot of developers have not known about the very different Object Oriented Programming techniques of Javascript. A lot of them stumble upon it or have transpilers to autogenerate javascript code from modern javascript framework. In this article, let’s try to decode “this” in a unique way.

What is the “this” keyword? A common answer is it is defined as the current context. It is commonly known that “this” keyword has been used for the longest time since C++ while defining properties and functions in classes.

I have a slightly different perception about “this” here. I shall be using the following diagram to give it an analogy of the active application workspace given to a process on the RAM.

Here, I am trying to use this analogy for browsers that interpret and execute Javascript and HTML applications. I’m sure this analogy will help you understand “this” better.


In the above diagram, I’m using the outer box to denote the Browser’s active memory (very synonymous to the RAM on desktops). When we load our Web application which essentially renders to having

HTML, Javascript, CSS on the client side (the user’s browser).

Take the example of the following code. Let’s relate it to the diagram in the box MyClientApp. The following code uses the “this” keyword at different levels.

1.       It uses it for GlobalPrefix, myClass

2.       It uses it to define the properties and functions inside myClass


Hence, what we can infer from the above example is

1.       “this” is used to indicate the global space in the application workspace of the browser’s memory

2.       “this” behaves like a public access specifier when scoped inside a class

3.       “this” is used to indicate the current context (as per textbooks)

Hope this article clears your perspective on “this” in javascript.


No comments:

Post a Comment