Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Introducing ES2015 Classes Sub-Classes

tal Shnitzer
PLUS
tal Shnitzer
Courses Plus 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,887 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.