Reputation: 3
what is wrong with this code? I want to make something similar to looped linkedlist.
<script type="text/javascript" charset="utf-8">
function LinkedText(text, nextLinkedText) {
this.text = text;
this.next = nextLinkedText;
this.AsNext= function() {
this.text = this.next.text;
this.next = this.next.next;
return this;
}
}
var first = new LinkedText('first')
var last = new LinkedText('last', first);
first.next = last;
alert(first.text); //show 'firts'
alert(first.AsNext().text); //show 'last'
alert(first.AsNext().text); //show 'last' not 'first' why?
alert(first.AsNext().text); //show 'last'
alert(first.AsNext().text); //show 'last' not 'first' why?
</script>
Upvotes: 0
Views: 317
Reputation: 4367
Rewrite GetNext:
this.GetNext = function() {
return this.next;
}
It makes no sense to re-assign this.text in GetNext when all you want is to get the linked node and access it's text.
You can use it like this:
var i = 0 // avoid infinite loop below
var maxruns = 10; // avoid infinite loop below
var node = first;
while(node){
doSomethingWithNode(node);
node = node.GetNext();
// avoid an infinite loop
i++;
if (i > maxruns) {
break;
}
}
Upvotes: 1