TypeScript

// 使用class类关键词来定义一个类
/**
 *  对象中主要包含两个部分
 *  属性
 *  方法
 */
class Person{
    /**
     * 直接定义的属性是实例属性, 需要通过对象的实力去访问;
     * const per = new Persion();
     * per.name
     */

    name: string = 'Alan';

    /**
     * 使用static开头的属性是静态属性(类属性),无需创建对象,可以直接通过类访问。
     * Persion.age
     */
   static age: number = 18;

    /**
     * readonly 标识只读属性,不能修改
     */
    readonly sex: string = 'male';

    // 定义方法
    /**
     * 如果方法以static开头,则方法是类方法,可以直接通过雷区调用
     */
    sayHello(){
        console.log("Hello")
    }
    static sayHelloWorld(){
        console.log("Hello world")
    }


}


const per = new Person();

console.log(per, 'per')
console.log(per.name);
// console.log(per.name, per.age);
console.log(Person.age);

per.name = 'Faye'; // 实例属性可直接修改
console.log(per.name);

// per.sex = 'Faye'; // 报错
console.log(per.sex);


per.sayHello();
Person.sayHelloWorld();
原文地址:https://www.cnblogs.com/ningxin/p/15107305.html