typescript继承和重写

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24147051/article/details/85062894

类的继承和重写

在这里通过一个例子,说一下typescript继承和重写

    //父类
     class Gege{
      public name:string;
      public age:number;
      public sex:string;
      public constructor(sex:string,name:string,age:number){
        this.name = name;
        this.age = age;
        this.sex = sex;
      }
      public say(){
        console.log("father-123456");
      }
      public sayHello(){
        console.log("father-123456");
      }
     }
    
     let ge:Gege = new Gege('youchen','boy',16); //和 constructor 保持一致
    
    //子类
     class Child extends Gege{
        public look:string = 'handsome';
        public play(){
          console.log("child-子类的一个方法!");
        }
        public sayHello(){
          super.sayHello();
          console.log("child-重写父类的方法,添加新的东西!");
        }
     }
    
     let child = new Child('xiaoxiao','boy',2);
    
     child.play();
     child.sayHello();

说明:

  1. 子类通过 extends 继承父类

  2. 子类可以重新定义父类中的方法进行重写(比如上面例子中的sayHello)

注意:

TS只能单层继承

猜你喜欢

转载自blog.csdn.net/qq_24147051/article/details/85062894
今日推荐