JS - Class | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

JS - Class

var myVar = new myClass("test"); myVar.appendChild("test2"); class myClass { constructor(name) { this.name = name; this.children = []; this.degree = /* ??? */; } appendChild(name) { this.children = new myClass(name); } } my goal is to replace the /* ??? */ by the degree of child the element in the object is. I know what I'm saying means nothing, but... In this example, the var "test" has the degree 0 because it's the parent of the class, and "test2" has the degree 1 cause its one of the children of the degree 0 (so n+1). if we do myVar.appendChild("test3"), then test3 has degree 1, but if we do myVar.test2.appendChild("test4") then test4 has degree 2. How to do it ?

1st Mar 2019, 8:55 AM
NoxFly
NoxFly - avatar
6 Answers
+ 6
I dont know if i have understood, but something like this can help you i think: constructor(name){ ...... this.degree= 0; ..... } appendChild(name){ this.children= new myClass(name); this.children.degree= this.degree+1; }
1st Mar 2019, 9:02 AM
KrOW
KrOW - avatar
+ 5
@krOW yes exactly ;) but created dynamically in js and show in html / css like game upgrade's trees
1st Mar 2019, 9:57 AM
NoxFly
NoxFly - avatar
+ 4
NoxFly ドăƒȘケン Then i suggest to create a general Tree class and subclass it for determinated use. In this way you can reuse it on different contexts
1st Mar 2019, 10:40 AM
KrOW
KrOW - avatar
+ 3
Yes I just was writing something like that ^^ thanks, like that I can see how other would do it :)
1st Mar 2019, 9:05 AM
NoxFly
NoxFly - avatar
+ 3
I had the idea for the subclass but I don't know how to use it for the tree. You can see what I'm doing here : https://code.sololearn.com/W0uoMZItkTp6/?ref=app But I stopped, I'll continue it later so a method isn't finished yet
1st Mar 2019, 12:23 PM
NoxFly
NoxFly - avatar
+ 2
👍👍👍 i suppose than you have to build a tree-like data structure
1st Mar 2019, 9:07 AM
KrOW
KrOW - avatar