"this" is very confusing i know , but we will try our best to grab "this" .
so what is "this" actually means .
this represents an object that executes the current function.
window is the global object in case of javascript, its name defer with the resp to language for eg. in Nodejs , it is called global.
so, when we type window in console of our browser , we will get a object having all global JavaScript objects, functions, and variables.
Even the document object is a property of the window object.
you can read more about window later , but now we have to discuss about This . as you have seen that previous code, after typing window we get a object which is the same as we get when we type this , so why we get the result ? bcz as per defination , this refers to the object it belongs to.
The JavaScript this has different values depending on where it is used and how the code is written . so we will discuss this on different places and then observe its action.
First case : Only this
when we write only this it means it refer to the global object we have seen previously.
Second case : Inside Object
we have create a object name as username which has a variables firstname , lastname and a function fullname .
inside fullname function we console this
Output :
In this example , we can see inside username object we have a member function "fullname" which is console logging this . In the console we can see here this represent the object that execute cuurent function , that is username . let's see what happen if we use fat arrow function instead of normal function .
"this" in Fat arrow function
output
so why we got "code waala" as a output and now this is refering to window object instead of username object , why this is happening when everything is going good .
The thing is that arrow function deals with this keyword in a different way , They don’t define their own context since they doesn’t have its own this context. They inherit that from the parent scope whenever you call them whereas regular function takes the this context of the object under which function isexecuting.
so when arrow function is called it will take this object from its parent , in our case the parent is window because it is calling in window object.
Third case : constructor function
so what are contruction functions ? constructor functions doesnt have any value , they are designed to create new objects .
In the above code , we can see we have created a constructor function username . and from that constructor function we have create two username user1 & user2 .
In case of user1 we got a output "code waala" and this is refering to username object and same for user2 .
but we have covered that member function take this context of the object which is executing them, in case of constructor function this represents to the newly create object as seen in output.
Hope you found something useful..
Top comments (0)