Particularly in JavaScript object oriented programming:
If I have a class like this, for example:
class Animals{
constructor(name, species){
this.name = name;
this.species = species;
}
}
Why do we need to use this.yyyy = yyyy in the constructor? I have read explanations many times but still can’t get it, please explain like I’m 5
In: 28
It is because Javascript does not enforce the fact 2 variables accessible in the same scope must be written differently. So if you don’t put the this it will use the locally defined one, the one received in parameter. If your member variable was written differently you would not need the this.
Some languages prevent you from doing that, they will throw an error saying duplicate variable name or something like that which will force you to use proper naming so your code is easier to read.
Latest Answers