跳转至

05类

定义类

Text Only
class 类名 {
    属性名: 类型;

    constructor(参数: 类型){
        this.属性名 = 参数;
    }

    方法名(){
        ....
    }

}

示例和使用

TypeScript
class Person{
    // 定义实例属性,需要通过对象的实例去访问
    name:String="lily";
    // 在属性前使用static关键字可以定义类属性(静态属性)
    // 静态属性(类属性),可以直接通过类去访问
    static age:number=18;
    // 不能后续修改
    readonly fullName:string="lily lee";

    //定义方法
    sayHello(){
        console.log("hello, world");
    }
    static sayHello1(){
        console.log("hello, world");
    }
}

const person=new Person();
console.log(person.name);
console.log(Person.age);
person.sayHello();
Person.sayHello1();