frankarendpoth/frankarendpoth.github.io

Class Inheritance Issues

Opened this issue · 2 comments

Hi,
thank you for the Tutorial on the Platformer Game (https://github.com/frankarendpoth/frankarendpoth.github.io/tree/master/content/pop-vlog/javascript/2018/006-rabbit-trap). I really enjoyed watching it. While implementing an own version of it, I recognized an issue with how you implement the "class inheritance".

The way you do it is the following:

Superclass = function(){
    //Definition of Superclass attributes
}
Superclass.prototype = {
    //Definition of Superclass methods
}
Subclass = function(){
    Superclass.call(this);
    //Definition of Subclass attributes
}
Subclass.prototype = {
    //Definition of Subclass methods
}
Object.assign(Subclass.prototype, Superclass.prototype);
Subclass.prototype.constructor = Subclass;

This seems to work for your approach, but as soon as you want to override methods, your implementation leads to always calling the superclass' method instead of the subclass one (Similar to the constructor, that you also had to fix after the assignment).

A nicer way of implementing your approach, and also have the correct overriding behavior would be to turn around the assignment and e.g. use the following instead:

Superclass = function(){
    //Definition of Superclass attributes
}
Superclass.prototype = {
    //Definition of Superclass methods
}
Subclass = function(){
    Superclass.call(this);
    //Definition of Subclass attributes
}
Subclass.prototype = Object.assign(Object.create(Superclass.prototype), {
    //Definition of Subclass methods
});

That way, the subclass' prototype methods correctly overwrite the Superclass once. Method overriding works as intended. No need to fix constructors.

Best,
Daniel