I create a function that returns an object to store a number, along with some methods to manipulate the number.
const StoreX = (x) => ({
x,
add1: () => x + 1,
inc1: () => { x += 1; },
getX: () => x,
});
const value = StoreX(10);
If I run value.add1() a couple of times, it always returns 11. When I inspect the value object, its x property remains as 10. This is expected as add1() simply returns x + 1.
I expect the inc1() method to update the x property of the object. But when I run the value.inc1() a few times, the result isn't what I expected.
value.inc1(); // value.x === 10
value.inc1(); // value.x === 10
value.getX(); // 12
So somehow value.x remains at 10. But if I run value.getX(), I do get the "correct" 12. So inc1() appears to be updating some other instance of x that can only be retrieved by getX().
What's happening here ?
inc1is mutating the parameterx, not the object propertythis.x.this), so you can't use arrow function as constructor