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 Getters and Setters Object Interaction

Naoki Yoshida
Naoki Yoshida
6,984 Points

Phone property results undefined, help!

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 owner() {
     return this._owner;
   }

   set owner(owner) {
       this._owner = owner;
      console.log(`setter called: ${owner}`);
   }

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

class Owner {
  constructor (name, address) {
    this.name = name;
    this.address = address;
  }

  set phoneNumber(phone) {
    const phoneNormalized = phone.replace(/[^0-9]/g, '');
    this._phone = phoneNormalized;
  }

  get phone() {
    return this._phone;
  }

}

const ernie = new Pet('cat', 4, 'persa','miooou');
const vera = new Pet('dog', 8, 'border collie', 'woof woof');

ernie.owner = new Owner ('Naoki', 'Furogori 202');
ernie.owner.phone = '(090)4235-4545';

console.log(ernie.owner);

2 Answers

Steven Parker
Steven Parker
215,954 Points

In the video, the setter for the phone number is simply named "phone". But in this code it is named "phoneNumber", so it does not get called when you assign ernie.owner.phone = '(090)4235-4545';.

Change the setter function name to "phone" to fix the error.

Naoki Yoshida
Naoki Yoshida
6,984 Points

It worked! Thanks! I hope to get better in those typos.