typeScript 之 (8) 继承,重写,super

super是什么?

在类方法中, super 就表示当前类的父类

class Animal{
    name:string
    age:number
    constructor(name:string,age:number){
      this.name=  name
      this.age = age
    }
    sayHello(){
      console.log('动物在叫');
      
    }
  }

  class Dog extends Animal{
     sayHello(){
        super.sayHello(); 
    }

  }

 

 

使用继承该如何写?

 

在没有使用继承前,狗和喵喵在学说话如何写?

(function(){
  //定义一个表示狗的类
  class Dog{
    name:string
    age:number
    constructor(name:string,age:number){
      this.name=  name
      this.age = age
    }
    sayHello(){
      console.log('汪汪汪');
      
    }
  }

  class Cat {
    name:string
    age:number
    constructor(name:string,age:number)
    {
      this.name = name
      this.age = age
    }
    sayHello(){
      console.log('喵喵喵');
      
    }
  }

  const dog = new Dog('旺财',18)
  const cat  = new  Cat('咪咪',10)
  dog.sayHello()
  cat.sayHello()

}())

 

posted @ 2021-05-09 16:25  zmztyas  阅读(430)  评论(0编辑  收藏  举报