+ 2

why is the word "this" necessary?

13th Aug 2016, 9:17 PM
Zac Stan
Zac Stan - avatar
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!
17th Aug 2016, 2:49 PM
Max
Max - avatar
0
Thanks Max👍 You solved my problem.
8th Sep 2016, 12:14 PM
MANOJ KUMAR BERA
MANOJ KUMAR BERA - avatar
- 2
To select the recent object or variable we use this keyword
14th Aug 2016, 9:51 AM
Adityapratap singh Rajput
Adityapratap singh Rajput - avatar