I have a Campaign object with a campaign_offer array property which contains N CampaignOffer children.
My goal is to access to the Campaign object inside each CampaignOffer object.
To achieve this, I've added in the CampaignOffer object a parent property which contains the Campaign object.
// Parent
var Campaign = function (properties) {
this.id = properties.id || null;
this.campaign_offer = [];
};
// Parent: Add a new child in array of children
Campaign.prototype.addOffer = function (offer) {
// Pass the parent reference to the child
offer.parent = this;
this.campaign_offer.push(offer);
};
// Child
var CampaignOffer = function (properties) {
this.name = properties.name || null;
this.parent = properties.parent || null;
};
// ---------------------------------------------
// Create the parent
var campaign = new Campaign({ id: 1 });
// Create the child
var campaign_offer = new CampaignOffer({ name: 'test' });
console.log('Offer without parent', campaign_offer);
// Add the child to the parent
campaign.addOffer(campaign_offer);
console.log('Offer with parent', campaign_offer);
You can see the result there: Fiddle
The problem is that when you browse the second console.log(). You can find too much recursiveness. Like:
parent.campaign_offer[0].parent.campaign_offer[0].parent.campaign_offer[0]...
I understand this output but don't know how to avoid this. What about defining a max depths?
Btw it doesn't make an infinite loop.
CampaignOffermight need to reference aCampaignobject, but I can't see any reason for the converse. (I'd also call itcampaignrather thanparent, but that's a style thing.) You can do that, and it's harmless unless you write code that tries to traverse it and doesn't understand that it may circle back, but I don't see any need for it.