簡體   English   中英

類構造函數(ES6)中的Java語言調用類

[英]Javascript calling class within class constructor (ES6)

我正在嘗試用javascript實現一個簡單的Stack(我知道可以用一個簡單的數組來實現,但這不是我的意思。)因此,這是我的設計:

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屬性,該屬性跟蹤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對象。

有什么建議嗎?

您正在將堆棧與數據混淆。 您的代碼嘗試執行的操作是將整個堆棧壓入構造函數中的堆棧,這可能會遇到無限遞歸的情況。

定義什么data ,可以將其轉換為Data類,或者將其視為Array。 在您的Stack構造函數中,只需將數據(作為原始數據或作為類Data的實例)推入堆棧中即可。

如果要將堆棧實現為鏈接列表,則該列表需要在某個點結束,其“ next” /“ top”引用為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
  }
  …
}

我將把方法的實現留給讀者練習。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM