In trying to port a Java app to JavaScript, I'm attempting the following inheritance technique:
var grandchild = new Grandchild();
Function.prototype.extend =
function(parent) {
var parentPrototype = parent.prototype;
this.prototype = Object.create(parentPrototype);
this.prototype.superPrototype = parentPrototype;
this.prototype.superConstructor = parent;
this.prototype.constructor = this;
}
;
function Parent(){
this.doStuff();
}
Parent.prototype.doStuff =
function() {
}
;
Child.extend(Parent);
function Child(){
this.superConstructor.call(this);
}
Child.prototype.doStuff = function() {
this.superPrototype.doStuff.call(this);
}
Grandchild.extend(Child);
function Grandchild(){
this.superConstructor.call(this);
}
Grandchild.prototype.doStuff = function() {
this.superPrototype.doStuff.call(this);
}
It works to one level of inheritance (i.e. var child = new Child()
) but with new Grandchild()
it throws an Uncaught RangeError: Maximum call stack size exceeded
because it gets stuck in infinite recursion on function Child()
.
- What exactly is happening and why?
- How can I tweak this technique so it allows me to call
this.superConstructor.call(this)
andthis.superPrototype.doStuff.call(this)
as shown without hitting the infinite recursion on the immediate parent?
It works when I specify the super class in the calls as follows, but I would prefer not to have to do this:
function Child(){
Parent.call(this);
}
Child.prototype.doStuff = function() {
Parent.prototype.doStuff.call(this);
}
function Grandchild(){
Child.call(this);
}
Grandchild.prototype.doStuff = function() {
Child.prototype.doStuff.call(this);
}