Write an inheritance with combinatorial inheritance, and you can't get a method on the parent prototype chain.

topic description

I want to write an inheritance in which an instance of a subclass can inherit the methods and properties of the parent class

sources of topics and their own ideas

related codes

function Animal (name) {
    this.name = name || "Animal";
    this.sleep = function () {
        console.log(this.name + "" + "eatting")
    }
}
Animal.prototype.eat = function (food) {
    console.log(this.name +"" + food)
}

function Cat(name, food) {
    Animal.call(this, name)
    // console.log(Animal.name, name)
    this.food = food || "meat"
}
extend (Animal, Cat)
function extend (subClass, superClass) {
    subClass.prototype = new superClass()
    subClass.prototype.constuctor = subClass //
}
const cat = new Cat("haixin", "fish")
console.log(cat.name) // haixin
console.log(cat) // Cat { name: "haixin", sleep: [Function], food: "fish" }
//catAnimaleat
cat.eat() // TypeError: cat.eat is not a function

what result do you expect? What is the error message actually seen?

I thought the newly generated cat instance could get the methods and properties on Cat and Animal, but the eat method on the prototype chain on Animal couldn"t get it. I don"t know why? And why the constuctor property of subClass.prototype in the extend method points back to subClass?

Mar.29,2021

  1. because you write this sentence in reverse extend (Animal, Cat) , it should be the child class before the parent class, that is, the correct one is extend (Cat, Animal) .
  2. The constuctor attribute of
  3. subClass.prototype points back to subClass?
    new Cat, and you get an instance of cat. How do you know that it was created by that class, that is, you know it comes from the class Cat by visiting cat.constructor. The actual cat instance of
    does not have this property of its own. It points to the prototype property of the parent class, that is, Cat.prototype, through its own _ _ proto__ attribute, and then finds the contructor in it.
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b37aee-2b8fd.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b37aee-2b8fd.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?