Search code examples
javascriptinheritanceprototype

javascript - prototype inheritance from generic to specific - better way


I am trying to make more clean way to do this:

let Mammal = {
    purr: function () {
        console.log("it's sound is:", this.sound)
    }
}

let Cat = {
    sound: "meow"
}

Cat.__proto__ = Mammal;
let purrer = Object.create(Cat)
purrer.purr(); // it's sound is: meow

Right now the code works as intended. Object "purrer" inherits "sound" property from "Cat" prototype, and "Cat" inherits method "purr" from "Mammal" Prototype. However i feel that line

Cat.__proto__ = Mammal 

is somehow wrong, unelegant and i should not make nested inheritance that way. Can you please confirm that and advice how to make it "good way"? i want to achieve the same result so the purrer inherits data from both Cat and Mammal

Thank you!


Solution

  • You are right using '__proto____' is horrible issue,you should not change already created object prototype, it is wrong semantically and it can cause performance problems. Why you have this problem ? Answer is easy` your oop modeling is wrong. This is how you should do

    class Mammal {
        constructor() {
            this.sound = "Mammal sound";
        }
        purr() {
            console.log("it's sound is:", this.sound)
        }
    }
    
    class Cat extends Mammal {
        constructor() {
            super();
            this.sound = "meow"
        }
    }
    
    let purrer = new Cat();
    purrer.purr(); // This also will meow