我有一个具有campaign_offer
数组属性的Campaign
对象,它包含N个CampaignOffer
子对象。
我的目标是访问每个CampaignOffer
对象中的Campaign
对象。
为了实现这一点,我在CampaignOffer
对象中添加了一个包含Campaign
对象的parent
属性。
// 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);
您可以在这里看到结果:
问题是,当您浏览第二个console.log()
。你会发现太多的递归性。如:
parent.campaign_offer[0].parent.campaign_offer[0].parent.campaign_offer[0]...
我理解这个输出,但不知道如何避免。那么如何定义最大深度呢?
顺便说一下,它不会产生无限循环
我理解这个输出,但不知道如何避免。那么如何定义最大深度呢?
你这里没有多重深度,可以说,你只有一个循环引用:
<>之前/---------------------------------------------------------------------| +----------------+ |+->| campaign | |+----------------+ || id: XXX | +----------+ || campaign_offer |-------->| (array) | |+----------------+ |----------+ +----------------+ || 0 |------->| campaign_offer | |+----------+ +----------------+ ||名称:XXX | || parent |——/+----------------+之前循环引用是很好的,只要你不编写遍历它们的代码而不知道它们可能存在,因为这些代码可能会永远循环下去。
在这种情况下,我没有看到任何需要,似乎CampaignOffer
有Campaign
是有意义的,但我没有看到太多指向相反(campaign_offer
数组)。但是,还是那句话,没关系,只是不要写代码试图遵循它们的结尾,因为它们没有结尾