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 Object-Oriented JavaScript Working with Classes in JavaScript Adding Methods To Our Class

Gremyko Coleman
Gremyko Coleman
8,876 Points

Adding Method

In this example, why is the method created outside of the constructor? couldn't it be created inside the constructor as well, and still work the same?

1 Answer

Steven Parker
Steven Parker
210,475 Points

The method is intended to accessed on any class instance, so it's defined in the class. Anything defined inside the constructor would be limited in scope and could only be accessed from inside the constructor.

Gremyko Coleman
Gremyko Coleman
8,876 Points

ooooh, I see, thanks it makes sense now

Tibor Ruzinyi
Tibor Ruzinyi
16,582 Points

Hello Steven, why is this not working ? Its giving an error : Unexpected token { We never declare a method inside a constructor ?

class Pet {
  constructor(animal, age, breed, sound) {
    this.animal = animal;
    this.age = age;
    this.breed = breed;
    this.sound = sound;
    speak () {                            //=>Unexpected token {
      console.log(this.sound);
    }
  }
}
Steven Parker
Steven Parker
210,475 Points

That message seems pretty clear, your "speak" method is being declared inside the constructor. Just move it out (but still inside the class).

And for the best chance for your question to be seen, always start a fresh one instead of creating one as a comment or "answer" to a previous question.