I am trying to create a function that returns an object and a function that reset this object to its initial state. Something like:
const create = () => ({
a: "something"
});
const setup = () => {
let obj = create();
const reset = () => {
obj = create();
}
return {
obj,
reset
}
}
const { reset, obj: myObj } = setup();
myObj.b = 2;
reset();
console.log("expected to be undefined", myObj.b);
But when I call the function and uses the reset function, it doesn't reset the object. myObj.2 still contains 2. I expected the reference to myObj to stay the same, so when we call reset obj becomes a new object and myObj's reference points to that new object.
After some fiddling around I realized that my function works if I do this instead:
const create = () => ({
a: "something"
});
const setupWithGet = () => {
let obj = create();
const getObj = () => obj;
const reset = () => {
obj = create();
}
return {
getObj,
reset
}
}
const { reset, getObj } = setupWithGet();
getObj().b = 2;
reset();
console.log("expected to be undefined", getObj().b);
Why do I need to use a new function here?
The object returned by
setup()contains a reference to the original value ofobj. When you reassignobjit doesn't change this reference, it still refers to the original object. It's not linked to the variable in any way.You don't need any of the methods or scope issues to demonstrate this. See the simple code here:
Reassigning
objhas no effect on thecontainerobject. Its reference is to the original value ofobj.In your second version,
getObjis a closure that references the local variableobj, not the object. Reassigning the variable updates the variable in that scope, and the function returns that new value.