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 trialDominik Hentschel
793 PointsJS 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!
1 Answer
Travis Alstrand
Treehouse Project ReviewerHey Dominik Hentschel 👋
I would think that using
set childEdges(edge) {
this._childEdges.push(edge);
}
Would work when setting it with node.childEdges = edge
. I don't have a playground in front of me to test with so I could be wrong but I feel that should work.
The downside is that node.childEdges = edge
looks like an assignment when it's really an addition.
Me personally, the class method you have above
addChildEdge(edge) {
this._childEdges.push(edge);
}
would have been my approach as well.
Dominik Hentschel
793 PointsDominik Hentschel
793 PointsHey Travis Alstrand,
thank you very much for your answer! :-)
Now I understand how that could have been implemented and its downside when setting new edges.
It is very valuable for me to understand how to code my real projects in a clean way.
I'll keep my class method for this specific porpose.
Thank you!
Travis Alstrand
Treehouse Project ReviewerTravis Alstrand
Treehouse Project ReviewerYou're very welcome! 😃