+ 1

Constructor Error

When I run this JS I get TypeError, here is the source code: var cur, render; class node { //NODE CONSTRUCTOR constructor(x){ this.elem = x; this.next = null; } } class llist { constructor(){ //LINKED LIST CONSTRUCTOR this.head = null; this.size = 0; this.push = addElement; } } function addElement(y){ //PUSH FUNCTION var node = new node(y); if (this.head == null) this.head = node; else{ cur = this.head; while (cur.next!=null) cur = cur.next; cur.next = node; } this.size++; } var myList = new llist(); myList.push("hello"); myList.push("world"); render = myList.head; //support variable for printing out the liked list for (let i=0; i<myList.size; i++){ document.write(render+" "); render = render.next; } Here is the TypeError: "Uncaught TypeError: node is not a constructor at llist.push" Why "var node = new node(y);" shouldn't be working as a constructor?

21st Apr 2020, 9:11 PM
Alessandro Palazzolo
Alessandro Palazzolo - avatar
2 Antworten
+ 1
You had a naming collision. node the variable and node the class.
21st Apr 2020, 10:28 PM
ChaoticDawg
ChaoticDawg - avatar
0
Figured out that replacing "node" with "Node" makes it working...but why? I haven't seen "node" among keywords in JS.
21st Apr 2020, 9:26 PM
Alessandro Palazzolo
Alessandro Palazzolo - avatar