类构造函数中的Javascript调用类(ES6)

时间:2018-06-15 09:25:09

标签: javascript ecmascript-6 es6-class

我试图在javascript中实现一个简单的堆栈(我知道它可以用一个简单的数组来实现,但这不是我的观点。) 所以这就是我的设计:

pop(): remove and return the item from the top of the stack
push(item): add the item at the top of the stack
peek(): return the item from the top of the stack
isEmpty(): return true if stack is empty

它有一个top属性可以跟踪顶部元素,这是我的类定义:

class Stack {
  constructor(data) {
    this.data = data;
    this.next = null;
    this.top = Stack(data);    // <- Here's my problem
  }

  pop() {
    if(this.top == null) return new Error('Trying to pop, but the stack is empty.');

    let item = this.top.data;
    this.top = this.top.next;
    return item;
  }

  push(data) {
    let item = new Stack(data);
    item.next = this.top;
    this.top = item;
  }

  peek() {
    if(this.top == null) return new Error('Peeking the stack, but the stack is empty.');

    return this.top.data;
  }

  isEmpty() {
    return top == null;
  }
}

我希望top属性为Stack元素,但是,正如您所看到的那样,这会让我陷入无限循环。我可以top设置为具有data, next, and top的对象。但这是唯一的方法吗?也许我可以有一个成员函数在初始化类时生成top属性?但是,我最终还是要将其设置为对象而不是Stack对象。

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

您将堆栈与数据混淆。你的代码尝试做的是将整个堆栈推入构造函数的堆栈中,可能会进行无休止的递归。

定义data是什么,可能将其转换为类Data,或将其视为数组。在Stack构造函数中,只需将数据(作为原语或类Data的实例)压入堆栈。

答案 1 :(得分:1)

如果您希望将堆栈实现为链接列表,那么该列表需要在某个时刻结束,其中包含&#34; next&#34; /&#34; top&#34;引用为null

但是,您不应该将堆栈(表示整个事物,可能是空的)与堆栈元素(堆栈中的一个数据项)混淆。不要将它们混合到同一个类中,使用两个单独的类:

class StackElement {
  constructor(data) { // takes the data as an argument (possibly also `next`)
    this.data = data;
    this.next = null;
  }
}
class Stack {
  constructor() { // takes no arguments
    this.top = null; // initialises reference with nothing
    // has no other properties
  }
  …
}

我将这些方法的实施作为练习留给读者。