Why do we need THIS key word in constructors?

407 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

Have you ever heard about “shadowing” ? It’s when two objects have the same name, but one has been defined “closer to you”, so you see this one.

For instance :

let a = 1;
if (true){
let a = 2;
console.log(a);
}
console.log(a);

Will print 2, then 1. Inside of the “if”, there is a variable a declared that “hides in its shadow” the variable a that was 1.

So when you do

class Animals{
constructor(name, species){
this.name = name;
this.species = species;
}
}

Inside the constructor, what is “name” ? Well it’s the value that has been defined in the innermost block. But an “name” is defined right in the constructor : the parameter. So name will only refer to this parameter, and you can never access the attribute.So you say “this.name” to get the attribute : it’s the name inside “this”.

If I remember correctly, in JavaScript, you always have to say “this” before you access to an attribute. But in C++ for instance, those two would work :

class Animals
{
private:
std::string name;
std::string species;

public:
Animals(std::string name, std::string species)
{
this->name = name;
this->species = species;
};
}

class Animals2
{
private:
std::string m_name; std::string m_species;
public:
Animals2(std::string name, std::string species)
{
m_name = name;
m_species = species;
};
}

Because, in the second class, m_name is not shadowed.

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