Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.