TS 的类

一、基础语法

class Person {
    constructor() {

    }
}

二、类的属性

1、属性的初始化

在 TS 中,我们如果在要 constructor 中定义一个属性,必须先在 constructor 之前对数据进行初始化:

class Person {
    city: string;  // 初始化
    constructor() {
        this.city = '成都'
    }
}

属性在初始化的时候可以选择不设置初始值,但是就必须在 constructor 中进行赋值。

也可以在初始化的时候就设置一个初始值:

class Person {
    city: string = '四川';  // 初始化
    constructor() {
        // 
    }
}

2、属性的传值

class Person {
    city: string = '四川';
    name: string;
    constructor(name: string) {
        this.city = '成都'
        this.name = name;
    }
}
new Person('Lee');

3、静态属性

class Person {
    static country: string = '中国'
    city: string = '四川';
    name: string;
    constructor(name: string) {
        this.city = '成都'
        this.name = name;
    }
}
new Person('Lee');

三、类的方法

class Person {
    static country: string = '中国'
    city: string = '四川';
    name: string;
    constructor(name: string) {
        this.city = '成都'
        this.name = name;
    }
    // sayHello(name: string): void {
    //     console.log('hello' + name);
    // }
    sayHello = (name: string): void => {

    }
}
new Person('Lee');

四、类的继承

class Person {
    static country: string = '中国'
    city: string = '四川';
    name: string;
    constructor(name: string) {
        this.city = '成都'
        this.name = name;
    }
    // sayHello(name: string): void {
    //     console.log('hello' + name);
    // }
    sayHello = (name: string): void => {

    }
}

class Student extends Person {
    constructor(name: string) {
        super(name);
    }
}

子类的 constructor 中如果没有其他额外的属性,可以省略不写:

class Student extends Person {

}

如果子类有自己的属性:

class Student extends Person {
    age: number;
    constructor(name: string) {
        super(name);
        this.age = 20;
    }
}

五、访问修饰符

访问修饰符,用来修饰类里面的属性和方法:

修饰符含义作用范围
public(默认)公共类型当前类、子类、外部
protected受保护类型当前类、子类
private私有类型当前类
readonly只读类型当前类、子类、外部

示例代码:

class Person {
    protected city: string = '成都'
}

const p = new Person();
console.log(p.city);
私有类型的 getter 和 setter(扩展)
class Person {
    private _city: string = '成都'

    get city() {
        return this._city;
    }
    set city(value: string) {
        if (value === '四川') {
            this._city = value;
        }
    }
}

const p = new Person();
console.log(p.city);
p.city = '四川';
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值