JamesG
JamesG

Reputation: 2018

Keeping data in a constructor for use across multiple objects

I have a simple function which I use as a "parent" function in order to store data to be shared across multiple child objects. Here is my parent "Calc()":

function Calc() {
  this.hasBeenCalculated = {
    child1: false,
    child2: false,
  }
  this.updateGlobalCalculationState = ({calcType, hasBeenCalculated}) => {
    this.hasBeenCalculated[calcType] = hasBeenCalculated;
  }
}

Here is a "child" object that I want to update the Calc() above:

const ChildCalc1 = {
  setup() {
    // link up this object to the main Calc prototype
    Calc.call(this);
  },
  calculate() {
    this.updateGlobalCalculationState({calcType: 'child1', hasBeenCalculated: true})

  }
}
const ChildCalc2 = {
  setup() {
    // link up this object to the main Calc prototype
    Calc.call(this);
  },
  calculate() {
    this.updateGlobalCalculationState({calcType: 'child2', hasBeenCalculated: true})

  }
}

The children and parent are connected by the prototypes for each:

ChildCalc1.prototype = Object.create(Calc.prototype);
ChildCalc1.setup();
ChildCalc2.prototype = Object.create(Calc.prototype);
ChildCalc2.setup();

Each time a child has been calculated, I want it to update the parent Calc() "hasBeenCalculated" object, but when ever I call to update that object, it resets to the default. The object updates aren't persisting over the multple children.

Where am I going wrong here?

EDIT:

I've added an update for how each child is created.

Upvotes: 0

Views: 61

Answers (1)

Bergi
Bergi

Reputation: 664548

The children and parent are connected by the prototypes

They should not. You are looking to create a tree structure here. No inheritance is necessary for that. Your .prototype code doesn't even work as your children are not constructor functions.

You should just do

const parent = new Calc();
const childCalc1 = {
  parent,
  calculate() {
    this.parent.updateGlobalCalculationState({calcType: 'child1', hasBeenCalculated: true});
  }
};
const childCalc2 = {
  parent: parent,
  calculate() {
    this.parent.updateGlobalCalculationState({calcType: 'child2', hasBeenCalculated: true});
  }
};

There is only one Calc instance, the parent, and both your children refer to it.

You could potentially make it work by letting the child objects inherit from the parent object, but there's no point in that. Use composition over inheritance.

You might want to create a ChildCalc constructor/class however that takes the parent instance as an argument, and reduces code duplication between the children. You then would be able to just do

const parent = new Calc();
const childCalc1 = new ChildCalc(parent, 'child1');
const childCalc2 = new ChildCalc(parent, 'child2');

Upvotes: 2

Related Questions