0

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 ?

3
  • 2
    inc1 is mutating the parameter x, not the object property this.x. Commented May 22, 2018 at 19:50
  • 1
    arrow functions are not bind with context (this), so you can't use arrow function as constructor Commented May 22, 2018 at 19:54
  • 1
    @NobbyNobbs It's a factory function not a constructor Commented May 22, 2018 at 19:55

1 Answer 1

4

As @4castle said, your functions update the x variable (declared by the parameter) not the .x object property.

You have to use either a getter to make the property live

function StoreX(x) {
  return {
    get x() { return x; },
    add1: () => x + 1,
    inc1: () => { x += 1; },
    getX: () => x,
  };
}

or methods to use the property instead of the variable

function StoreX(x) {
  return {
    x,
    add1() { return this.x + 1 },
    inc1() { this.x += 1; },
    getX() { return this.x },
  };
}
Sign up to request clarification or add additional context in comments.

1 Comment

Just to add a bit of commentary on the difference between those solutions for those wondering: the first solution has more encapsulation because you can't set the internal x value from outside the StoreX function, while the second solution is more easily converted to class syntax, which can store the member functions once on the prototype object instead of duplicating them on every instance (saving memory).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.