【TypeScript教程】# 11:super关键字

说明

尚硅谷TypeScript教程(李立超老师TS新课)学习笔记。

super

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

如果在子类中写了构造函数,在子类构造函数中必须对父类的构造函数进行调用。

例子

(function() {
    
    
    // 父类
    class Animal {
    
    
        name: string;
        constructor(name: string) {
    
    
            this.name = name;
        }
        sayHello() {
    
    
            console.log("动物叫~");
        }
    }
    // 使Dog类继承Animal类
    class Dog extends Animal{
    
    
        age: number;
        constructor(name: string, age: number) {
    
    
            super(name); // 调用父类的构造函数
            this.age = age;
        }
        sayHello() {
    
    
            console.log(`${
      
      this.name}汪汪汪`);
        }
    }

    const dog = new Dog("小黄", 2);
    console.log(dog);
    dog.sayHello();
})()

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/kaimo313/article/details/127139419
今日推荐