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?