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

jamesjones21
jamesjones21
9,260 Points

Using an object literal to create an object with other objects as properties.

Hi All,

I was going to ask this on stack overflow but thought I would get rinsed for asking such a question :)

But I have just done the Object Oriented JS course, which I finished quite quick as I understand the concepts of OO from PHP.

So I have created two classes Dog and Owner, an I was tinkering about with creating an object literal to then set the properties to new instances of the created classes.

The Dog class is nothing special and hold only the constructor method which then sets 3 properties.

The Owner class has two setters and getters, but I'm wondering if the instantiate the Owner class to a property within the object literal named collection to hold this information.

the Dog and Owner Classes:

class Dog
{
    constructor (breed, name, age) 
    {
        this.breed = breed;
        this.name = name;
        this.age = age;
    }
}


class Owner
{
    set owner(owner)
    {
        this._owner = owner;
    }

    get owner () 
    {
        return this._owner;
    }

    set number(number)
    {
        this._number = number;
    }


    get number ()
    {
        return this._number;
    }
}

The collection object literal:

const collection = {

    ownerClass: new Owner(),
    setOwnerName: ownerClass.owner = 'David',
    setOwnerNumber: ownerClass._number = 1245,
    dogClass: new Dog('Pitbull', 'Kim', 10),

}

The error that is returned when I console.log collection it states ownerClass is not defined? To me setting the setters of owner and number for the Owner class won't be allowed in an object literal ?

1 Answer

Steven Parker
Steven Parker
229,644 Points

It looks like there are two issues with the object literal:

  • the method syntax is not correct
  • internal property cross-references are missing the "this." prefix
const collection = {
  ownerClass: new Owner(),
  setOwnerName() { this.ownerClass.owner = "David"; },
  setOwnerNumber() { this.ownerClass._number = 1245; },
  dogClass: new Dog("Pitbull", "Kim", 10)
};
jamesjones21
jamesjones21
9,260 Points

thank you, I was on the right track when I was using the this keyword to represent the collection object, but it was the change of methods instead of properties I needed to do :)