TypeScript-类

  • TS 中的类和 ES6 中的类 几乎 一样

阅读本章节之前建议先阅读一下以下的文章:

  1. 66-JavaScript-ES6类和对象
  2. 67-JavaScript-ES6继承

TS 中的类

  • 和 ES6 的区别, 需要先定义实例属性, 才能够使用实例属性
class Person {
    // 实例属性
    name: string;
    age: number;

    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }

    // 实例方法
    say(): void {
        console.log(`我的名称叫${this.name}, 我的年龄是${this.age}`);
    }

    // 静态属性
    static food: string;

    // 静态方法
    static eat(): void {
        console.log(`我正在吃${this.food}`);
    }
}

let p = new Person('BNTang', 18);
p.say();

Person.food = '蛋挞';
Person.eat();

TS 中的继承

class Person {
    // 当前实例的实例属性
    name: string;
    age: number;

    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }

    // 当前实例的实例方法
    say(): void {
        console.log(`我的名称叫${this.name}, 我的年龄是${this.age}`);
    }

    // 当前类的静态属性
    static food: string;

    // 当前类的静态方法
    static eat(): void {
        console.log(`我正在吃${this.food}`);
    }
}

let p = new Person('BNTang', 18);
p.say();

Person.food = '蛋挞';
Person.eat();


class Student extends Person {
    // 当前实例的实例属性
    book: string;

    constructor(name: string, age: number, book: string) {
        super(name, age);
        this.book = book;
    }

    // 当前实例的实例方法
    say(): void {
        console.log(`我是重写之后的say-${this.name}${this.age}${this.book}`);
    }

    // 当前类的静态方法
    static eat(): void {
        console.log(`我是重写之后的eat-${this.food}`);
    }
}

let stu = new Student('zs', 18, 'BNTang');
stu.say();
Student.food = '冰淇淋';
Student.eat();

end02

posted @ 2021-11-28 22:29  BNTang  阅读(34)  评论(0编辑  收藏  举报