JS console showing wrong results

62 Views Asked by At

I get a strange behaviour with Firefox when modifying a variable and displaying it (live demo here):

var MyModule = ( function() {
  var currentPosition = {x : 1, y : 2, z : 3};

  function changePosition() { currentPosition.x = 17; };

  return { changePosition : changePosition,    
           currentPosition : currentPosition };  
} )();

console.log(MyModule.currentPosition);  // 17, 2, 3 instead of 1, 2, 3 !!
MyModule.changePosition();
console.log(MyModule.currentPosition);  // 17, 2, 3

Why did this happen ? (Why does current.Position give 17 before it was modified to 17?)

More generally, how to get/set a variable in a Revealing Module Pattern?


Screenshot with Firefox:

enter image description here

2

There are 2 best solutions below

0
On

It looks like Firefox holds a reference to the object and when you inspect it you see its modified state in both cases.
Next time you can set a breakpoint on that line and watch the variables there. In my experience that is more reliable. When you change the log statements into logging the value instead of the object it will work always like expected.

console.log(MyModule.currentPosition.x);
MyModule.changePosition();
console.log(MyModule.currentPosition.x);

About the module pattern. You implemented it like it should :)
This is my no.1 source of javascript patterns. -> Module pattern

2
On

I am going to guess that you ran the 3 lines one after each other and when you inspect the first printed line there is a little i next to it. Chrome will report the the most recent attributes of an object not the value of them at time of printing so if you were to just print the currentPosition and not run changePosition() then you would see 1,2,3.