javascriptobject

Increase counter and dynamically change variable that relies upon it


how can I increment a counter and expect the incremented counter to be changed within the object value that is using it as well?

Imagine:

var pizzaOrder = {
    id: "pizza",
    counter: 0,
    sentence: this.id + this.counter // first problem is here  
    // as I am getting NaN
};

pizzaOrder.counter++;

console.log(pizzaOrder.sentence);

expected output:

"pizza1";

Solution

  • You can't reference an object that hasn't been finished being created yet like that, but it sounds like you'd want to use a getter here:

    var pizzaOrder = {
      id: "pizza",
      counter: 0,
      get sentence() {
        return this.id + this.counter;
      }
    };
    pizzaOrder.counter++;
    
    console.log(pizzaOrder.sentence);