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

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

Kylie Soderblom
Kylie Soderblom
3,885 Points

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