【问题标题】:Why am I able to use methods defined in one class in another separate class?为什么我可以在另一个单独的类中使用一个类中定义的方法?
【发布时间】:2021-09-29 08:23:50
【问题描述】:

这里我有两个类,Node 类和 LinkedList 类。我想知道为什么我能够在 LinkedList 类中使用 Node 类中的方法。

例如,在 LinkedList 类中,在 .addToTail() 方法中,我对初始化为“this.head”的 tail 变量使用 .setNextNode() 和 .getNextNode() 方法。由于“this.head”不是Node类的实例,它应该不能使用Node类中的方法,对吧……?还是我错过了什么?

class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
    getNextNode() {
        return this.next;
    }
    setNextNode(node) {
        if (node instanceof Node || node === null) {
            this.next = node;
        } else {
            throw new Error('Error!');
        }
    }
}

class LinkedList {
    constructor() {
        this.head = null;
    }
    addToHead(data) {
        let newHead = new Node(data);
        let currentHead = this.head;
        this.head = newHead;
        if (currentHead) {
            this.head.setNextNode(currentHead);
        }
    }
    addToTail(data) {
        let tail = this.head;
        if (!tail) {
          this.head = new Node(data);
        } else {
          while(tail.getNextNode()) {
            tail = tail.getNextNode()
          }
          tail.setNextNode(new Node(data));
        }
      }
}

【问题讨论】:

  • “既然“this.head”不是Node类的实例,它应该不能使用Node类中的方法,对吧……” - 尽管this.headnull 开头,但您的代码将其设置为带有this.head = new Node(data)this.head = newHead 的Node 实例
  • 谢谢你的回答,真的让我明白了!

标签: javascript class methods linked-list nodes


【解决方案1】:

您可以使用它们,因为您有一个分配给 head 的 Node 实例。您尚未添加任何可以设置限制使用这些功能的访问修饰符(例如私有)。

【讨论】:

  • 问题被标记为javascript:JavaScript(与TypeScript相反)没有访问修饰符,例如private。但是,它确实有 private fields 的语法。
【解决方案2】:

newHead 是 Node 的一个实例。设置 this.head 等于 newHead 意味着 this.head 现在也是 Node 的一个实例。您可以通过使用“instanceof”检查 this.head 来查看这一点。

addToHead(data) {
   let newHead = newNode(data);
   let currentHead = this.head;
   this.head = newHead;
   console.log(this.head instanceof Node); // returns true
   . . .
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多