I am trying to implement a stack in JavaScript that uses a nested class.
class Stack {
constructor() {
class Node {
constructor(val, pre) {
this.val = val;
this.pre = pre;
}
}
this.top = undefined;
}
push(val) {
this.top = new Node(val, this.top);
}
pop() {
let ret = this.top.val;
this.top = this.top.pre;
return ret;
}
isEmpty() {
return this.top === undefined;
}
}
With this code I get TypeError: Illegal constructor
as soon as the method push()
is called.
Apparently, I can create Node
objects only in the constructor of the stack. This is most likely because the nested class is in the constructor but putting it in directly into the other class creates syntax errors.
Does JavaScript not have nested classes like this? All I could find on the internet on nested classes were declarations of classes with the function
keyword like this one:
Nested class in JavaScript
However, that answer is before class
was added in 2015 (http://www.ecma-international.org/ecma-262/6.0/#sec-class-definitions), so I was wondering if that is possible now.