以下代码没有任何问题。它工作顺利。



class Animal{
  constructor(name,age){
    this.name = name;
    this.age = age;
  }
  getPrint(){
    console.log(`name: ${this.name}\nage:${this.age}`);
  }
};

class Cat extends Animal{
  getPrint(){
    super.getPrint();
  }
}


let animal = new Animal('miyav',9);
let cat = new Cat("mayov",12);
// cat.name = "mayov";
// cat.age = 12;
animal.getPrint()
cat.getPrint()





但是,当我尝试使用'return'编写上述代码时,出现错误。



class Animal{
  constructor(name,age){
    this.name = name;
    this.age = age;
  }
  getPrint(){
    return `name: ${this.name}\nage:${this.age}`;
  }
};

class Cat extends Animal{
  getPrint(){
    super.getPrint();
  }
}


let animal = new Animal('miyav',9);
let cat = new Cat("mayov",12);
console.log(animal.getPrint());
console.log(cat.getPrint());





我认为我已经解决了问题,但是我仍然不明白为什么。

如果我们在上面的代码中键入下面的代码,问题就解决了。但是如何?

class Cat extends Animal{}

最佳答案

正如注释中提到的@Pointy,第二个示例在return类的getPrint()方法中缺少Catsuper.getPrint()按预期从超类返回值,但是该值不会从子类的getValue方法返回。要解决此问题,只需将return添加到子类中的方法



class Animal{
  constructor(name,age){
    this.name = name;
    this.age = age;
  }
  getPrint(){
    return `name: ${this.name}\nage:${this.age}`;
  }
};

class Cat extends Animal{
  getPrint(){
    return super.getPrint();
  }
}


let animal = new Animal('miyav',9);
let cat = new Cat("mayov",12);
console.log(animal.getPrint());
console.log(cat.getPrint());





class Cat extends Animal{}起作用的原因是,由于您没有在子类中重新定义getPrint方法,因此它会自动从超类继承它(这可能是您想要的,因为您的getPrint方法没有做任何额外的事情)。因此,如果您声明了一个空的子类,它将获得超类的所有方法。

class Cat extends Animal{}
let cat = new Cat("mayov",12);
console.log(cat.getPrint());


之所以可行,是因为cat实例将使用通过getPrint关键字正确定义的超类的return方法。

关于javascript - 在“继承”中,我遇到了“返回”代码的麻烦,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55798885/

10-14 16:49
查看更多