To understand this thing, you need to know about function expression, lexical environment, prototype inheritance.
'this' keyword refers to the object it belongs to.
let say we have a class like this,
class Hello{
constructor(name){
this.name = name
}
hello(){
console.log(this.name);
}
}
now let's make a new object with the help of this class.
var person = new Hello('Alex')
Now I can do something like this,
person.hello();
This line will return 'Alex';
Now let's console.log(person);
console.log(person)
person ==> {
name : 'Alex'
<prototype> {
constructor: function Hello()
}
}
You will notice that Hello function is not at the top level of the person object. It is at the first prototype level of that object. Everything inside of this prototype will refer to the class or Factory function or
Constructor function that helps to define that person object. In this case, it refers to Hello class.
var person is defined on the global level. so when you call to person.hello() it will check at the top level of that object. If it is not in there, then it will go to the outside environment and try to find out what is this hello() thing. The outer environment of this person object is the global level. hello() function is not at the global level. When javaScript did not find the hello() in the outer environment then it will throw an error that saying hello() is undefined.
When we use 'this' keyword, it will say check on prototypes too. go through all the prototypes until you meet that thing. If it is not in there, then go outer environment and check if it is there.
'this' keyword will refer anything, to the object it belongs to. Also, remember everything in javaScript is an object expect primitive data