Yes i call this
key word in JavaScript the most scariest keyword because it kept confusing me for long time even though i was already a JavaScript developer, i encountered this key word when i started my journey as a React developer, let us see how we can make it easier to understand.
Impoorrtant :
this
keyword behaves differently when we use it in function and and object methods.
let us create a simple file called thisKeyWord.js
and add the following line of code
console.log(this) // {}
Inside the regular functions
let us create a function and do the following
function myFunction(){
console.log(this);
}
myFunction();
in the console we can see that its an global window object
Inside the object methods
let us add the following code in the file
let person = {
name : "Guru",
age : 29,
gender : "male",
getDetails() {
console.log(this);
}
};
person.getDetails();
in the console we can see that its the object itself
Summary
- Inside the regular functions ,
this
keyword is an global object - Inside the object methods its the defined object itself
I have explained in my youtube video also , please like, share and subscribe to my youtube cahnnel if you like my content
Top comments (1)
It's even scarier than that :D
Some comments have been hidden by the post's author - find out more