Introduction to this keyword
- this keyword in Javascript is used to refer to an object.
Behaviour of this keyword
Inside a function in the global space
When we declare a function inside the global space and use this, then it will print out window object. The reason behind this is this keyword will refer to the object. In the global space everything present is present inside the window object, hence we get that.
If it is inside the window object then can we invoke the function as object.function_name() as we do it when we have a class whose object is created like other programming languages?
The answer is yes we can do that. The object depending name will change depending on where we are running the js file.
What I mean is if we run it on the client side or in other words in the browser only then will the object's name be a window, if we run it on our desktop or server-side then it will be different
Example :
A variable in the global space
Again it refers to the window object
Inside a method inside a class
It refers to the class object Example:
Inside an object
Again refers to the object