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

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
231,261 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.

ooooh, I see, thanks it makes sense now

Tibor Ruzinyi
Tibor Ruzinyi
17,968 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
231,261 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.