JavaScript Introducing ES2015 Classes Sub-Classes

tal Shnitzer
PRO
tal Shnitzer
Pro Student 5,242 Points

re-assigning const? why re-define parent class "Person" properties- "name" and "age", in the child class "Student"?

in the following code the const "dances" is being re-define in the child class, how come it is not an error?

also

why " this.name = name; this.age = age;" being re-defined in "Student" child class? isn't the whole idea of inheritance is using what is already in the parent class.

class Person {
  dance() {
    const dances = [
      'waltz',
      'tango',
      'mambo',
      'foxtrot'
    ];
    console.log(`${this.name} is doing the ${dances[Math.floor(Math.random() * dances.length)]}!`);
  }
  constructor({ name, age, eyeColor = 'brown' } = {}) {
    this.name = name;
    this.age = age;
    this.eyeColor = eyeColor;
  }
}

class Student extends Person{
  dance(traditional) {
    if(traditional) {
      super.dance();
      return;
    }
    const dances = [
      'lyrical',
      'tap',
      'ballet',
      'jazz'
    ];
    console.log(`${this.name} is doing the ${dances[Math.floor(Math.random() * dances.length)]}!`);    
  }
  constructor({ name, age, interestLevel = 5 } = {} ) {
    super({name,age});
    this.name = name;
    this.age = age;
    this.interestLevel = interestLevel;
    this.grades = new Map;
  }
}

1 Answer

Andreas Nyström
Andreas Nyström
8,852 Points

The const "dances" is not globally outside the class scope. You can have the same const <variable> in every method if you want, because the scope is only in that method. For example.

// This will return hello and is ok because the const is in a method and cant get reached outside that method
myMethod1 () {
const string = 'hello';
return string
}

// This will return goodbye and is ok because the const is in a method and cant get reached outside that method
myMethhod2() {
const string = 'goodbye';
return string
}

The other question I'm not sure of to be honest. I wouldn't have written it like that. Hopefully someone else could help you out here.