I've stumbled upon a very odd issue in my last project. I've implemented inheritance as follows:
function Parent(){}
Parent.prototype.hi = function(){
alert("Parent: hi!");
};
Parent.prototype.bye = function(){
alert("Parent: bye!");
};
function Child(){
this.hi = function(){
alert("Child: hi!");
};
}
Child.prototype = new Parent();
This way I can override only the functions I need in the Child constructor, and the remaining will be inherited from the parent.
This works ok. Here's the test:
var test = function(){
var p = new Parent();
p.hi();
p.bye();
var c = new Child();
c.hi();
c.bye();
};
test();
And the output is the expected:
Parent: hi!
Parent: bye!
Child: hi!
Parent: bye!
However, when I store the instances in an array, the bye function in the children instance is not inherited, and it throws an error. Test code:
var anArray = [
new Parent(),
new Child()
];
var test2 = function(){
for(var i = 0, m = null; i < anArray.length; i++){
m = anArray[i];
m.hi();
m.bye(); //WTF not working for the child?
}
};
test2();
Output:
Parent: hi!
Parent: bye!
Child: hi!
TypeError: m.bye is not a function
I've spent more than an hour staring at this code and debugging it, and I can't see where is the problem. The original code was way more complex and had more functions. I think something is wrong with the array, but I don't want to give up on it because I think a table-driven method is the best approach for what I'm trying to implement.
1 Answer 1
The array with the new Child instance was created before you let Child inherit from Parent, and does still have the old prototype (without any methods). In contrast, the c = new Child is executed in the test() function after the Child.prototype = ... assignment.
Move the array declaration/initialisation into the test2 function. Or simply move all class stuff to the top.
1 Comment
Explore related questions
See similar questions with these tags.
Child.prototpyecannot change the prototype of existing instances.