JS console showing incorrect results

I am getting strange behavior with Firefox when changing 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 current.Position

gives 17

before it was changed to 17

?)

More generally, how to get / set a variable in a dropdown module template?


Screenshot from Firefox:

enter image description here

+3


source to share


2 answers


I'm going to assume you ran 3 lines one after the other, and when you check the first printed line, there is a little bit next to it i

. Chrome will report the last attributes of the object, not the value of them during printing, so if you just want to print the current position and don't run changePosition () then you will see 1,2,3.



+2


source


It looks like Firefox contains a reference to the object, and when you check it, you see its changed state in both cases.
Next time you can set a breakpoint on that line and look at the variables there. This is more reliable in my experience. When you change the log statements to log a value instead of an object, it will always work as expected.

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

      



About the module template. You have implemented it the way you want it :)
This is my javascript error source. β†’ Module diagram

+1


source







All Articles