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 trialTsipporah Christopher
Full Stack JavaScript Techdegree Graduate 15,593 Pointsphone.replace() doesn't work, and when I try to return the phone it comes back undefined
Hello I am having trouble getting the replace property to work. And later when I try to directly call the phone property it returns undefined. Thank you!
class Pet {
constructor(animal, age, breed, sound) {
this.animal = animal;
this.age = age;
this.breed = breed;
this.sound = sound;
}
get activity() {
const today = new Date();
const hour = today.getHours();
if (hour > 8 && hour <=20) {
return 'playing';
} else {
return 'sleeping';
}
}
get location() {
const today = new Date();
const day = today.getDay();
console.log(dayy);
if (day == 0) {
return 'outside';
} else {
return 'in the backyard';
}
}
get owner() {
return this._owner;
}
set owner(owner) {
this._owner = owner;
}
speak() {
console.log(this.sound);
}
}
class Owner {
constructor (name, address) {
this.name = name;
this.address = address;
}
set phone(phone) {
const phoneNumber = phone.replace(/[^\d]/g, '');
this._phone = phoneNumber;
}
get phone() {
return this._phone;
}
}
const golden = new Pet('dog', 1, 'pug', 'bow wow');
const charm = new Pet('dog', 8, 'border collie' , 'woof woof');
golden.owner = new Owner('Isis', '123 main street');
golden.owner.phoneNumber = '(123) 456-7890';
console.log(golden.owner);
console.log(golden.owner.name);
console.log(golden.owner.phone);
1 Answer
Steven Parker
231,268 PointsThe phone.replace() code looks good, but it isn't being used here. The setter code only runs when you assign something to the phone property, but the later code is creating a new property named "phoneNumber" instead.
That's also why the getter for phone returns "undefined", as the backing value has never been created.