javascript中的变异?

javascript中的变异?,javascript,linked-list,Javascript,Linked List,在下面的代码中,size2()方法工作正常。但在size1()中,它正在变异对象并使其为null。为什么size2()中没有发生这种行为 在我看来,这两种方法看起来都一样,但它们之间有细微的不同。在size2()中,您没有对this.head进行变异,因为您首先将引用复制到局部变量中。因为在while循环中您正在变异本地节点=节点。下一步从这里开始节点和这个头不再链接。这是永恒的价值/参考 下面是一篇关于它的javascript文章its,因为当您在下一次调用size2 its时,由于使用变量n

在下面的代码中,size2()方法工作正常。但在size1()中,它正在变异对象并使其为null。为什么size2()中没有发生这种行为

在我看来,这两种方法看起来都一样,但它们之间有细微的不同。

在size2()中,您没有对this.head进行变异,因为您首先将引用复制到局部变量中。因为在
while循环中
您正在变异本地
节点=节点。下一步
从这里开始
节点
这个头
不再链接。这是永恒的价值/参考
下面是一篇关于它的javascript文章

its,因为当您在下一次调用size2 its时,由于使用变量node,size2()方法中没有出现突变,这是为什么?
class Node {
    constructor(data, next = null) {
        this.data = data;
        this.next = next;
    }
}

class LinkedList {
    constructor() {
        this.head = null;
    }

    insert(data) {
        this.head = new Node(data, this.head);
    }

    size1() {
        var counter = 0;
        while (this.head) {
            counter++;
            this.head = this.head.next;
        }
        return counter;
    }

    size2() {
        var counter = 0;
        var node = this.head;
        while (node) {
            counter++;
            node = node.next;
        }
        return counter;
    }
}
var list = new LinkedList();
list.insert(35);

console.log(list);
console.log(list.size2());