当子类继承父类之后就会自动拥有父类的非私有的成员信息

1.extends

  1. //申明类
  2. class Person {
  3. //属性,成员变量
  4. name: string = "张三";
  5. age: number;
  6. //构造函数,创建对象会默认调用的方法
  7. constructor(name: string, age: number) {
  8. this.name = name;
  9. this.age = age;
  10. }
  11. //定义方法,成员方法
  12. //成员变量,成员方法只能由当前对象调用,当前类无法直接调用
  13. sayHello(msg: string="默认信息"): void {
  14. console.log(this.name + msg);
  15. }
  16. }
  17. //student继承当前person类的方法与属性
  18. class Student extends Person{
  19. }
  20. let p2=new Student("王兄下",23)
  21. p2.sayHello()

2.super

  1. //申明类
  2. class Person {
  3. //属性,成员变量
  4. name: string = "张三";
  5. age: number;
  6. //构造函数,创建对象会默认调用的方法
  7. constructor(name: string, age: number) {
  8. this.name = name;
  9. this.age = age;
  10. }
  11. //定义方法,成员方法
  12. //成员变量,成员方法只能由当前对象调用,当前类无法直接调用
  13. sayHello(msg: string="默认信息"): void {
  14. console.log(this.name + msg);
  15. }
  16. }
  17. //student继承当前person类的方法与属性
  18. class Student extends Person{
  19. //这里是学生自己的属性
  20. gender:string;
  21. constructor(name:string,age:number,gender:string){
  22. //调用父类的构造函数初始化name和age的信息
  23. //这里的super一定在第一个
  24. super(name,age)
  25. //初始化自己的gender信息
  26. this.gender=gender;
  27. }
  28. sayHello(msg: string="默认信息"): void {
  29. //利用super调用父类的方法
  30. super.sayHello();
  31. //打印当前子类的信息
  32. console.log("当前性别是:",this.gender)
  33. }
  34. }
  35. let p2=new Student("王兄下",23,"男")
  36. p2.sayHello()