Axel186
Axel186

Reputation: 561

Javascript - OOP reference loop

I trying to create Object-"Room" that have another objects-"Items". I want that every "Item" will have a reference to "Room".

I just want to know what is the "Room" of some "Item"...

Here is the problem :

// Creating Room Class
function Room(name){
  this.name = name;
  this.items = [];
};

// function that creates item in a Room
Room.prototype.addItem = function(name){
    var newItem = new Item(name, this);
    this.items.push(newItem);
}

// Creating Items Class
function Item( name, room ){
    this.name = name;
    this.parentRoom = room; // HERE IS THE PROBLEM!!
    // I need reference to my Room Class
};


// Lets create a Room
var myRoom = new Room('MyRoom');

// And lets add some items
myRoom.addItem("chair");
myRoom.addItem("bed");
myRoom.addItem("computer");

// Result -> you can see endless loop of Rooms in th Items
console.log( myRoom );

You can see in Inspect element endless loop.

Screenshot from Inspect element

Or what is the right way to create this thing? I need to use "extends" method for "Item" Class to "Room"?

Upvotes: 1

Views: 343

Answers (1)

Jeff Dale
Jeff Dale

Reputation: 76

There is nothing wrong with un-ending object references when you inspect an javascript object. They essentially form a cyclic graph in object references.

However, this means that you get the benefits AND shortfalls of cyclic graphs.

When traversing/iterating through the graph, You need to be careful of infinite loops by keeping track of what objects you've already visited and do not visit them more than once. (i.e. by keeping track of a visited map)

Upvotes: 4

Related Questions