0

I am fairly new to oop in js. I know the basics of proto and prototype but I am not sure my problem is causing from them. I also dig into this keyword cant find anything solution-kindly. Anyways my code is here.(Normally I would expect change at only speedy object but I read somewhere that hamster.stomach changes, still dont really know the reason tho, so my question is why hamster.stomach changes and why hamster.legs is not.)

let hamster = {
  stomach: [],
    legs: 4,
  change_leg(n){this.legs = n;},
  eat(food) {
    this.stomach.push(food);
  }
};

let speedy = {
  __proto__: hamster
};

let lazy = {
  __proto__: hamster
};

// This one found the food
speedy.eat("apple");
speedy.change_leg(10);
alert( speedy.stomach ); // apple
alert(speedy.legs);
alert(hamster.legs);
alert( hamster.stomach ); // apple```
urbanassa
  • 9
  • 3
  • `change_leg` mutates the `speedy` object, not the `hamster` and not the `lazy` one. In contrast, `eat` does mutate the `.stomach` array - the single, shared array being referenced thrice. – Bergi Dec 15 '20 at 17:00
  • @Bergi so, it is caused by the characteristic of array right. If there is an string property or boolean etc. those wont be changed too. – urbanassa Dec 15 '20 at 17:21
  • Yes, the array is a mutable object on its own. – Bergi Dec 15 '20 at 17:23

0 Answers0