gpt4 book ai didi

javascript - 为什么在节点更改时在原型(prototype)内部分配 var node=this.obj 而不是 this.obj?

转载 作者:行者123 更新时间:2023-11-30 16:42:00 24 4
gpt4 key购买 nike

我正在使用原型(prototype)在 javascript 中实现一个简单的链表。我遇到了一些我不太明白的东西 -

var Node = function( value ) {
this.value = value;
this.next = null;
};

var List = function( head ) {
this.head = null;
};

List.prototype.insert = function( value ) {
if ( this.head === null ) {
this.head = new Node( value );
} else {
var aNode = this.head;
console.log( 'same: ' + (aNode === this.head)); // prints true
while ( aNode.next !== null ) {
aNode = aNode.next;
}
var node = new Node( value );
aNode.next = node;
console.log( 'Head: ' + this.head.value ); //prints 1
console.log( 'Node: ' + aNode.value ); //prints 2,3,4
}
};

var aList = new List();
aList.insert( 1 );
aList.insert( 2 );
aList.insert( 3 );
aList.insert( 4 );

如果 this.head 和 aNode 共享一个引用,将 aNode 更改为 aNode.next 不会更改 this.head。有人可以解释为什么吗?我是原型(prototype)新手。

最佳答案

因为操作顺序。你想要括号:

console.log( 'same: ' + (aNode === this.head))
// ---------------------^-------------------^

没有他们,它是有效的

console.log( ('same: ' + aNode) === this.head)

...(这当然是错误的)因为 + 有一个 higher precedence===。这与当 a1if (a + 5 === 6) 为 true 的原因相同。

关于javascript - 为什么在节点更改时在原型(prototype)内部分配 var node=this.obj 而不是 this.obj?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31814666/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com