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

What does the speak() method works here? and how to use it as I don't see it in the constructor method

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

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

2 Answers

Hi Hanwen!

The method does NOT need to be part of the constructor because it does not require any initialized value.

It does, use the "sound" property value, however, which IS initialized in the constructor.

Consider this code:

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

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

const myPet = new Pet('dog', 4, 'pit bull', 'snarl');

myPet.speak();

It will log "snarl", to the console.

I hope that helps.

Stay safe and happy coding!

Understood now, Thank you Peter

the constructor includes only properties! Methods are included inside the new class object but outside of the constructor function.

class NewClass {        // new class  blueprint for all future instances

   constructor (animal, age) {   // only properties
        this.animal = animal;
        this.age = age;
      }

speak()                       // new methods inside new class

anotherMethod()  
}

// note the word 'function' is not used when adding methods inside a class