一. ts类详解

1. 类的定义

class Person {
    // 属性
    name: string
    age: number
    // 构造函数
    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }
    // 普通方法
    eating() {
        console.log(`${this.name}[${this.age}岁], is eating`);
    }
}

// 调用
const p=new Person('ypf',18);
console.log(p.name);
console.log(p.age);
p.eating();

2. 类的继承

 通过extends关键字继承父类
// 1.父类
class Person {
    // 属性
    name: string = ''
    age: number = 0
    // 构造函数
    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }
    // 普通方法
    eating() {
        console.log(`${this.name}[${this.age}岁], is eating`);
    }
}

// 2. 子类 
// 通过extends关键字继承父类
class Student extends Person {
    sno: number = 0
    constructor(name: string, age: number, sno: number) {
        super(name, age);
        this.sno = sno;
    }
    studying() {
        console.log(`姓名为:${this.name},年龄为:${this.age},学号为:${this.sno} 正在学习中....`)
    }
}

// 调用
const student = new Student('ypf', 18, 1001);
student.studying();
View Code

相关文章:

  • 2021-07-23
  • 2022-12-23
  • 2021-12-05
  • 2021-12-06
  • 2021-06-24
  • 2021-06-16
  • 2021-08-29
猜你喜欢
  • 2021-11-28
  • 2022-12-23
  • 2022-12-23
  • 2021-08-20
  • 2022-12-23
  • 2021-12-19
相关资源
相似解决方案