class类的用法

188 阅读2分钟

class类的定义

class 就是面向对象开发时,将对象具体定义成一个模块,来规范他的属性和行为。

class Person {
    name: string;
    age: number = 18;
    id: number;
    constructor(id: number, name: string) {
        this.id = id;
        this.name = name
    };
    introduce(): string {
        return `Hello, I'm ${this.name}, and i'm ${this.age} years old.`
    };
}

对象创建

let a = new Person("张三", "1");
a.name;
a.introduce();

静态成员

静态成员是只属于类本身,而不是属于对象。上面定义的属性,都是属于对象a的。

// 创建静态成员
class Person {
    static count: number = 1;
}
class Utils {
    static toLower(str: string): string {
        return str.toLowerCase()
    }
}
// 调用静态成员
Person.count;
Utiles.toLower("Hello World");

继承

继承后可新增属性,也可修改父类的属性和方法。

class Students extends Person {
    classNumber: string;
    constructor(id: string, name: string, classNumber: string) {
        // 要继承父类的属性,必须要用super方法接一下
        super(id, name);
        this.classNumber = classNumber;
    };
    
    introduceStudent(classNumber: string):string {
        return `Hello, I'm ${this.name}, and i'm ${this.age} years old.I'm a student`
    };
    
    // 上面的方法换一种写法,直接调用父类的方法来用
    introduceStudent(classNumber: string):string {
        return `${this.introduce()}.I'm a student`
    };
    
    // 覆盖父类introduce方法
    // 由于想调用父类方法中introduce()方法,用this调用之后,就相当于调用当前的introduce方法,会导致无限循环调用,导致内存溢出,报错
    // 调用父类的方法,可以用super来调用
    introduce(classNumber: string):string {
        // return `${this.introduce()}.I'm a student`;
        return `${super.introduce()}.I'm a student`
    };
    
}

let s = new Students(1,"张三", "三年二班")
s.id;
s.introduce();
// 父类子类的方法都可以调用
s.introduceStudent();

访问修饰符

用于控制类成员的可访问性 public private protected

private: 私有属性,只能在声明他的类中使用 protected: 属性是受保护的。只能在声明他的类和子类中使用。 public: 共有的。默认值

ts接口 interface 用类实现

interface 作为规范,让类去遵守,确保可以实现一些特定的功能。

interface Person {
    id: string;
    name: string;
    age: number;
    
    introduce(): void; 
}

class Student implements Person {
    name: string;
    age: number = 18;
    id: number;
    constructor(id: number, name: string) {
        this.id = id;
        this.name = name
    };
    introduce(): string {
        return `Hello, I'm a student`
    };
}

多态

使同一类型的对象,有不同的行为

// 借用上面的person接口,再次创建一个类

calss Teacher implements Person {
    name: string;
    age: number = 18;
    id: number;
    constructor(id: number, name: string) {
        this.id = id;
        this.name = name
    };
    introduce(): string {
        return `Hello, I'm a teacher`
    };
}

let s: Person = new Student();
let t: Person = new Teacher();
s.introduce()
t.introduce()

上面同一个类型的两个对象,在执行相同的方法时,具有不同的表现,就是多态