I have this setter, but I don’t know why set value and it doesn’t change :
this.setHead = function(head){
console.log('Head: x:'+this.getHead().getX()+' y:'+this.getHead().getY());
console.log('temp Head: x:'+head.getX()+' y:'+head.getY());
this.head = head;
console.log('Head: x:'+this.getHead().getX()+' y:'+this.getHead().getY());
}
And the result in Chrome log is :
Head: x:5 y:10 // old value
temp Head: x:1 y:7 //temporary value decide to copy
Head: x:5 y:10 // and the new valụe : NO CHANGE
I have read that Javascript pass object by reference, I don’t know does it difference with Java. If not, I don’t know why happen that. Please tell me.
Thanks 🙂
@ Edited : I have add a line for log, and see strange result :
console.log('Head: x:'+this.head.getX()+' y:'+this.head.getY());
Head: x:1 y:7
It’s strange, because I think it should be same with below line but It don’t
console.log(‘Head: x:’+this.getHead().getX()+’
y:’+this.getHead().getY());
And my getHead() is :
this.getHead = function() {
return head;
}
Javascript doesn’t pass anything by reference, setting
this.headdoesn’t magically makeheadrefer to something else (which is what by reference implies)Your
.getHead()method returnshead, notthis.head, so the assignment doesn’t affectgetHead()at all. They refer to different objects.Try this:
Basically what you have is most likely:
the
setHeadsets object property, where asgetHeadreturns theheadvariable passed to the constructor when initialized.To avoid this confusion you should just stick to object properties and prototypes and it’s all very simple: