1

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.

niklassc
  • 597
  • 1
  • 9
  • 24
  • 2
    How about this answer? It was around the same time `class` was added https://stackoverflow.com/questions/28784375/nested-es6-classes – Alberto Rivera Nov 17 '17 at 18:09
  • Yes, thanks! That does look like the answer to my question, I should have researched more, I did not see that one. Can I somehow close this question or redirect it to that answer or should I delete it? – niklassc Nov 17 '17 at 18:17

0 Answers0