Javascript object reset not working
That is because you are re-assigning a reference to the same object.
What your are overlooking in your code
You are using an IIFE (Immediately-Invoked Function Expression) to initially assign the value {x: 0}
to MyObject
. You are not assigning a function to MyObject
:
var MyObject = (function() {
return {
x: 0
}
})();
console.log(MyObject); // { x: 0 }
That is because the IIFE only executes once and then ceases to exist. When you then do var myObject = MyObject;
you are not creating a copy of MyObject
but just another reference to the object { x: 0 }
:
var a = {x: 0};
var b = a;
console.log(b); // {x: 0}
b.x = 10;
console.log (a); // 10
console.log (b); // 10
That is why your myObject = MyObject;
does not reset anything because you are actually just restating that myObject
should point to the same object as MyObject
.
How you can make it work
Change your code to:
var MyObject = function(){
return {x: 0}
}
var myObject = MyObject();
myObject.x+=1;
console.log(myObject.x); // 1
myObject = MyObject();
console.log(myObject.x); // 0