Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Dominik Hentschel
Dominik Hentschel
517 Points

JS Class - how to store dynamic objects to an object

I have a program to setup a graph network. Up to now I stored all class properties in the constructor and created methods to add values to properties which are not known upon creation of the objects:

class Node { constructor(name){ this.name = name; this.parentEdge = ''; this.childEdges = []; } addParentEdge(edge){ this.parentEdge = edge; } addChildEdge(edge){ this.childEdges.push(edge); } }

Recently I learned in my js course to store dynamic properties not in the class constructor but to use getters and setters.

For the parentEdge that works quite well. set parentEdge(edge) { this._parentEdge = edge; }

But for the ChildEdges I don't want to set a whole array with all childEdges at once but just to push one new array entry when needed.

I am happy for any help, thanks a lot!