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

Tebibu Kelelew
Tebibu Kelelew
5,750 Points

Is there something wrong with my code? I keep getting a "Cannot set property 'phone' of undefined" error

My code was a bit different when I initially got the error, but it doesn't seem to be working even when I basically directly copied over the code from the video; am I missing something?

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

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

  info() {
    console.log(`${this.name} is a ${this.age} year old ${this.breed}; when provoked ${this.name} makes a "${this.sound}" sound.`);
  }

  get activity() {
    const time = new Date();
    const hour = time.getHours();

    if(hour > 8 && hour >= 20){
      return `${this.name} is currently playing around!`;
    }else{
      return `${this.name} is currently sleeping!`;
    }
  }

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

}

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

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

  get phone() {
    return this._phone;
  }

}

const ernie = new Pet('ernie','dog',1,'pug', 'Yip! Yip!');
const vera = new Pet('vera','dog',8,'border collie', 'Woof! Woof!');

ernie.owner = new Owner('Teb', '123 Main Street');
ernie.owner.phone = '(206)123-4568';

console.log(ernie.owner);

1 Answer

The error occurs because: when you give a pet an owner, the owner is set as a private property (see the set owner method). But on following line, you're trying to access the pet's owner as if it's a normal property:

ernie.owner.phone = '(206)123-4568';

I haven't done that course in a while and am not super familiar with the code. Let me know if this helps!

Tebibu Kelelew
Tebibu Kelelew
5,750 Points

Thank you for the help! I totally forgot to even look at the setter at that time.