我有一个 Campaign
对象,其中包含一个 campaign_offer
数组属性,其中包含 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);
您可以在那里看到结果:Fiddle
问题是当您浏览第二个console.log()
时。你会发现太多的递归性。喜欢:
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?
这里没有多个深度,可以说,你只有一个循环引用:
/---------------------------------------------------------------------\ | +----------------+ | +->| campaign | | +----------------+ | | id: xxx | +----------+ | | campaign_offer |-------->| (array) | | +----------------+ |----------+ +----------------+ | | 0 |------->| campaign_offer | | +----------+ +----------------+ | | name: xxx | | | parent |--/ +----------------+
只要您编写的代码不会在不知道它们可能存在的情况下遍历它们,循环引用就可以了,因为该代码最终可能会永远循环。
在这种情况下,我认为没有任何需要,CampaignOffer
拥有Campaign
似乎是有意义的,但我不认为没有看到太多相反的意义(campaign_offer
数组)。但同样,没关系,只是不要编写试图遵循这些内容直至结束的代码,因为它们没有结束。
关于Javascript 从子方法访问父属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33149208/