【发布时间】: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.head以null开头,但您的代码将其设置为带有this.head = new Node(data)和this.head = newHead的Node 实例 -
谢谢你的回答,真的让我明白了!
标签: javascript class methods linked-list nodes