这是一个带有 super 关键字的继承示例
class Animal {
constructor(animalName, country) {
this.animalName = animalName;
this.country = country;
}
update(animalName=null, country=null) {
if (animalName) {
this.animalName = animalName;
}
if (country) {
this.country = country;
}
}
show() {
console.log("A");
console.log("Animal Name: ", this.animalName);
console.log("Animal Country: ", this.country);
}
}
animal = new Animal("Elephant", "India");
animal.show();
animal.update();
animal.show();
animal.update("Dog");
animal.show();
animal.update(null, "Africa");
animal.show();
animal.update("Whale", "Antartica");
animal.show();
class Whale extends Animal {
constructor(name, animalName, country) {
super(animalName, country);
this.name = name;
}
updateName(name=null) {
if (name) {
this.name = name;
}
}
show() {
console.log("W");
super.show();
console.log("Penguin Name: ", this.name);
}
}
whale = new Whale("Ele", "Whale", "Goa");
whale.show();
whale.updateName();
whale.show();
whale.updateName("Molly");
whale.show();
whale.updateName(null);
whale.show();
animal.update("Ants");
whale.show();
animal.update(null, "Australia");
whale.show();
animal.update("Mites", "New Zealand");
whale.show();
class Penguin extends Animal {
constructor(name, animalName, country) {
super(animalName, country);
this.name = name;
}
updateName(name=null) {
if (name) {
this.name = name;
}
}
show() {
console.log("P");
super.show();
console.log("Penguin Name: ", this.name);
}
}
penguin = new Penguin("Molly", "Penguin", "Goa");
penguin.show();
penguin.updateName();
penguin.show();
penguin.updateName("Pikachu");
penguin.show();
penguin.updateName(null);
penguin.show();
animal.update("Cat");
penguin.show();
animal.update(null, "Russia");
penguin.show();
animal.update("Seal", "Artic");
penguin.show();
您可以在此处尝试此代码:https ://repl.it/@VinitKhandelwal/inheritance-javascript