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
Other answers have explained the concept of [shadowing](https://en.wikipedia.org/wiki/Variable_shadowing), which is a related concept:
// Create variables named ‘a’ and ‘b’ on the “outside”
let a = 1;
let b = 2;
function doAThing() {
// Create a new variable, also named ‘a’ on the “inside”:
let a = 10;
// We are “inside” the function, so this will look for a variable
// named ‘a’ that exists on the “inside” first. In this case, we find
// the one above.
console.log(a); // Prints “10”
// There is no “inside” version of ‘b’. But there is an “outside”
// version of ‘b’ that we can use as a fallback. So we use that.
console.log(b); // Prints “2”
// At the end of the function, the “inside” version of ‘a’ is destroyed.
}
doAThing();
// We are “outside” the function now, so the “outside” value for ‘a’ is
// used here.
console.log(a); // Prints “1”
But when it specifically comes to classes and class methods, it’s a little more nuanced. Consider:
let name = ‘Kevin’;
class Animal() {
constructor() {
let name = ‘Chris’;
}
}
let a = new Animal();
console.log(a.name); // “undefined”
A constructor is just a special function. So in most ways, it behaves like any function would. In this example, we’re creating an “inside” version of the variable `name`, and assigning it the value `’Chris’`. But in the previous example, it was shown that all “inside” variables defined in functions like this get destroyed when the function runs to completion. This is also true inside of constructors. If you ran this code, the `Animal` you create won’t have a name set on it.
If you want to attach a value to the instance of the class you’ve created, you need to explicitly tell JavaScript to do that. The `this` keyword inside of classes is how you do that:
class Animal() {
constructor() {
// ‘name’ here is just an “inside” variable that will be destroyed when
// the constructor finishes
let name = ‘Kevin’;
// ‘this.name’ tells JavaScript that you want this variable to persist
// on the class instance
this.name = ‘Chris’;
}
}
let a = new Animal();
console.log(a.name); // “Chris”
In fact, the `this` keyword is nothing more than a variable that magically holds the same thing the constructor will eventually return. So this:
class Animal() {
constructor(name, species) {
this.name = name;
this.species = species;
}
}
let a = new Animal(‘Chris’, ‘cat’);
console.log(a.name); // “Chris”
Is basically identical to this:
class Animal() {
constructor() {
// Do nothing at all
}
}
let a = new Animal();
a.name = ‘Chris’;
a.species = ‘cat’;
console.log(a.name); // “Chris”
Latest Answers