I thought I had a good understanding on how to properly extend classes in JavaScript, but when extending a subclass I run into an endless loop when I override a method, and the call the parent method from the child class. I'm either doing it wrong, or you just shouldn't subclass this way in JavaScript.
Can anybody help educate me please?
var Grand = function() {
this.test();
};
Grand.prototype.constructor = Grand;
Grand.prototype.test = function() {
console.log( "Grand!")
};
var Parent = function() {
this.supr.constructor.call( this );
};
Parent.prototype = Object.create( Grand.prototype );
Parent.prototype.constructor = Parent;
Parent.prototype.supr = Grand.prototype;
Parent.prototype.test = function() {
this.supr.test.call( this );
console.log( "Parent!" );
};
var Child = function() {
this.supr.constructor.call( this );
};
Child.prototype = Object.create( Parent.prototype );
Child.prototype.constructor = Child;
Child.prototype.supr = Parent.prototype;
Child.prototype.test = function() {
this.supr.test.call( this );
console.log( "Child!" );
};
var g = new Grand(); // Outputs "Grand!"
var p = new Parent(); // Outputs "Grand!" "Parent!"
var c = new Child(); // Error: Endless Loop!
I would expect the console to log "Grand!", "Parent!", "Child!" when instantiated a new Child(), but instead I get an endless loop.
I'm coming from an ActionScript background, so creating classes in JavaScript still throws me some curve balls. Thanks for the help in advance!