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 trialBrian Prouty
Front End Web Development Techdegree Student 10,143 PointsWhat if you wanted to have the speak method be determined from the type of animal?
Say that you wanted the speak() method to be determined by the type of animal, would you be able to run an if statement like this:
class Pet {
constructor(animal, age, breed) {
this.animal = animal;
this.age = age;
this.breed = breed;
}
speak(){
if( this.animal === 'dog') {
console.log('woof');
} else if (this.animal === 'cat') {
console.log('meow');
}
}
}
Or would you run into a scoping issue?
1 Answer
KRIS NIKOLAISEN
54,971 PointsHere is a detailed article on variables and scope where he states
The this keyword is used to define object properties. Once defined in constructor, they become available for access in all class methods via the this keyword
So yes this.animal
is available to the speak()
method