从子方法访问父属性

Javascript Access to parent properties from child method

本文关键字:属性 访问 子方法      更新时间:2023-09-26

我有一个具有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 |——/+----------------+之前

循环引用是很好的,只要你不编写遍历它们的代码而不知道它们可能存在,因为这些代码可能会永远循环下去。

在这种情况下,我没有看到任何需要,似乎CampaignOfferCampaign是有意义的,但我没有看到太多指向相反(campaign_offer数组)。但是,还是那句话,没关系,只是不要写代码试图遵循它们的结尾,因为它们没有结尾