0

console.log(myDog) before and after myDog.eatTooManyTreats() prints two different values, 12 and 13. Can't really understand why that's happening, isn't objects passed by reference, which means they can't have two different states. Thanks for your attention.

const dogFactory = (_name, _breed, _weight) => {
  return dogObj = {
    _name, 
    _breed,
    _weight,
    get name () {
      return this._name;
    },
    get breed () {
      return this._breed;
    },
    get weight () {
      return this._weight;
    },
    set name (value) {
      return this._name = value;
    },
    set breed (value) {
      return this._breed = value;
    },
    set weight (value) {
      return this._weight = value;
    },
    bark() {
      return console.log('ruff! ruff!');
    },
    eatTooManyTreats() {
      return this._weight++;
    }
  }
}

const myDog = dogFactory('Dodo', 'Milk', 12);
console.log(myDog);                          // weight is 12

myDog.eatTooManyTreats();
console.log(myDog);                          // weight is 13
rigan
  • 27
  • 4
  • 2
    "_isn't objects passed by reference_" But you don't pass any object when you call the function `myDog.eatTooManyTreats();`. It is not really clear what exactly you expected to happen. – takendarkk Aug 12 '21 at 14:15
  • 6
    Not sure I understand. `eatTooManyTreats` changes the weight, and you display the weight before and after. You're the one changing the state. – Dave Newton Aug 12 '21 at 14:18
  • 1
    The object has two different states, just not at the same time. Notice that `console.log` (in the stack snippet, at least) prints the result as a string immediately; it doesn't [keep a reference (like some other consoles do)](https://stackoverflow.com/q/23392111/1048572). – Bergi Aug 12 '21 at 14:19
  • @takendarkk The method call *does* pass the object reference `myDog` to `eatTooManyTreats` as the `this` argument – Bergi Aug 12 '21 at 14:21

0 Answers0