+ 2
why is the word "this" necessary?
3 Réponses
+ 21
I struggled with this before! Hopefully this makes sense: The keyword "this" indicates that the following should be a property to the object being constructed.
For example, imagine a "person" object constructor:
function person(person_name, person_hobby) {
this.name = person_name;
this.hobby = person_hobby;
}
if we omitted the "this." part of a statement in the constructor, we would simply have "name = person_name;". That doesn't make sense! We are trying to show javascript that we want to add a property to the object we are constructing. BUT HERE'S THE CHEEKY BIT: since we can't know the name of the 'person' object beforehand (eg it could be Greg, or it could be Henna, or Melon -- or any other allowed javascript variable name) we can't say "Greg.name = person_name;". Thus, we use "this", which will reference to WHATEVER the name of the object happens to be! Problem solved!
0
Thanks Max👍 You solved my problem.
- 2
To select the recent object or variable we use this keyword