TypeScript函数与类声明

本文最后更新于:2023年7月28日 凌晨

ES6 class了解更多

🔗前往查看

🍒基础使用

constructornew关键字调用的构造函数

1
2
3
4
5
6
7
8
class Speaker {
name: string // 指定属性类型
constructor (name: string) {
this.name = name
}
}

const speaker: Speaker = new Speaker('Jonathan')

🍒继承

📌基础子类

1
2
3
4
5
6
7
class Say extends Speaker {
sayHi() {
console.log(`My name is ${this.name}.`)
}
}

const say: Say = new Say('Jonathan') // Say继承了Speaker的属性与方法

📌重写构造函数

1
2
3
4
5
6
7
8
9
10
11
12
13
class Introduce extends Speaker {
sex: boolean
age: number
constructor (name: string, sex: boolean, age: number) {
super(name);
[this.sex, this.age] = [sex, age]
}
myIntroduce () {
console.log(`I am a ${this.age}-year-old ${this.sex? 'boy': 'girl'} `)
}
}

const introduce: Introduce = new Introduce('Jonathan', true, 20)

🍒修饰符

📌public(默认)

使用public修饰的属性/方法可被子类使用

1
2
3
4
5
6
7
8
class Speaker {
public name: string
public constructor (name: string) {
this.name = name
}
}

const speaker: Speaker = new Speaker('Jonathan')

📌private

1
2
3
4
5
6
7
class Speaker {
private name: string
private constructor (name: string) {
this.name = name
}
}

📌protected

1
s

📌readonly

只读属性应在初始化时赋值(不同于const该属性还可在构造函数内赋值)

1
2
3
4
5
6
class Speaker {
readonly name: string = 'Jonathan'
constructor (name: string) {
this.name = name
}
}

📌参数属性

给构造函数的参数添加修饰符后参数成为类的属性

1
2
3
4
5
6
7
class Message {
constructor (readonly name: string, public age: number, private sex: boolean) {}

message () {
console.log(`${this.name} is a ${this.age}-year-old ${this.sex? 'boy': 'girl'}.`)
}
}

🍒存取器

给类添加get(),与set()接口来修改(读取)属性

1
2
3
4
5
6
7
8
9
10
11
class Message {
constructor (public name: string, public age: number) {}

get () {

}

set () {

}
}

TypeScript函数与类声明
https://qingshaner.com/TypeScript类class/
作者
清山
发布于
2022年1月3日
许可协议