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

andrew wolff
andrew wolff
5,980 Points

Why is the sound parameter available outside of the constructor.

The title says it all, how is sound in the constructor visible to the function after? Thanks

class Pet {
  constructor(animal, age, breed, sound) {
    this.animal = animal;
    this.age = age;
    this.breed = breed;
    this.sound = sound;
  }

  speak() {
    console.log(this.sound)
  }
}

1 Answer

Hi Andrew,

The constructor takes in the properties that belong to the class objects. So, every instance of the class will possess those properties taken in by the constructor. The scope is not limited to the constructor method alone, the properties are absorbed into the instance of the class created when the constructor is called.

So, every instance of Pet will have the ability to hold those four properties. As such, they can be accessed from within the instance using the methods within the class.

I hope that makes sense; else shout back and I'll do a better job!!

Steve.

andrew wolff
andrew wolff
5,980 Points

Thanks, that does make sense.

Good! Glad to have helped. :smile:

Enjoy the courses!

Steve.