I want to have an object that inherits an array property and a method to add elements to the inherited array. However, the inherited method yChange()
changes the prototype array and not the inherited array. This question explains why the undesired behavior happens. But can't figure out how to get the desired behavior.
var parent = {
x: 0,
y: [],
xChange: function () {this.x += 1},
yChange: function () {this.y.push(1)}
};
var child = Object.create(parent);
child.xChange();
child.yChange();
console.log(child.x, child.y); // 1 [1]
console.log(parent.x, parent.y); // 0 [1]
Desired:
console.log(child.x, child.y); // 1 [1]
console.log(parent.x, parent.y); // 0 []