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

Andrew Stewart
Andrew Stewart
7,999 Points

TypeError: Cannot set property 'phone' of undefined

I know this question has already been asked (was attributed to a type in that case). I have checked several times for typos.

I keep getting the following error: "TypeError: Cannot set property 'phone' of undefined
at Object.<anonymous> (/home/treehouse/workspace/Pet.js:54:19)"

Any ideas?

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';
    }
  }

  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 phone(phone) {
    const phoneNormalized = phone.replace(/[^0-9]/g, '');
    this._phone = phoneNormalized;
  }

  get phone() {
    return this._phone;
  }

}

const ernie = new Pet('dog', 1, 'pug', 'yip yip');
const vera = new Pet('dog', 8, 'border collie', 'woof woof');

ernie.owner = new Owner('Ashley', '123 Main Street');
ernie.owner.phone = '555-551-8971';

console.log(ernie.owner);

1 Answer

The Pet class is missing the following getter:

get owner(){ return this._owner; }

Andrew Stewart
Andrew Stewart
7,999 Points

Brilliant. Thanks for the speedy response!