I'm trying to use inheritance in JavaScript here, and I found problem having array value in Parent class that is inherited by a Child class. Below code is normal inheritance:
var Parent = function() {
this.list = [];
};
var Child = function() {};
Child.prototype = new Parent;
Child.prototype.constructor = Child;
var obj1 = new Child;
obj1.list.push("hello");
console.log(obj1.list); // prints ["hello"];
When I initialized new Child object (inherits Parent which contains array variable named list) to obj1 and tried to push obj1.list with a value "hello", obj1.list prints ["hello"] .. so far so good.
The problem comes when I did the above example and I tried to initialize new Child object to obj2 then push obj2's list with a value "goodbye", and obj2.list now prints ["hello", "goodbye"]. (See the code below:)
var obj2 = new Child;
obj2.list.push("goodbye");
console.log(obj2.list); // prints ["hello", "goodbye"];
I might have a misconception here, but the list array in Parent is somehow retaining the value and I don't know why.
This is a big trouble because if I reuse the Parent class to many other child classes like the case above, if Parent has array variable shared to its child classes, the value will be shared to the other child classes as well, which is unexpected for me.
What I expected is, the Child class represents new object, same goes to Parent class when Child class is initialized to obj1, which then when I initialize new Child object to obj2, the pushed value from obj1 should not be shared with obj2.
-- Question --
Can anyone help me find out why the list (the array variable of Parent) in the example above retains the values/share the values that are initiated by the Child objects (in above case, obj1 and obj2)?
If you have another solution that could solve this problem, it will be very nice of you, but I'll be happy to find out the problem above first.