Why do we need THIS key word in constructors?

417 views

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

6 Answers

Anonymous 0 Comments

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.

You are viewing 1 out of 6 answers, click here to view all answers.