1. (function () {
    2. // 定义一个animal类
    3. class Animal{
    4. name: string;
    5. age: number;
    6. constructor(name: string, age: number) {
    7. this.name = name;
    8. this.age = age;
    9. }
    10. sayHello() {
    11. console.log("动物在叫");
    12. }
    13. }
    14. /*
    15. 此时Animal被称为父类,Dog被称为子类
    16. 使用继承后,子类将会拥有父类所有的方法和属性
    17. 通过继承可以将多个类中共有的代码写在一个父类中,
    18. 如果希望在子类中添加一些父类中没有的属性或方法直接加就行了
    19. 如果在子类中添加了和父类相同的方法,则子类方法会覆盖掉父类方法
    20. 这种子类覆盖掉父类方法的形式,我们称为方法的重写
    21. 父类的静态方法及属性会被子类继承,但不能被子类重写
    22. */
    23. // 定义一个表示狗的类
    24. class Dog extends Animal{
    25. run() {
    26. console.log(`${this.name}在跑。。。`);
    27. }
    28. sayHello() {
    29. console.log("汪汪汪");
    30. }
    31. }
    32. // 定义一个猫的类
    33. class Cat extends Animal {
    34. sayHello() {
    35. console.log("喵喵喵");
    36. }
    37. }
    38. const dog = new Dog("旺财", 5);
    39. const cat = new Cat("旺财", 5);
    40. })()