Typescript 的 class 类是 js 中类的超集,在原有 js 标准 class 基础上,提供更加丰富的修饰符,默认情况下,所有的属性类型都是 public,可以自由访问,另外提供只允许在 class 内部访问的 private 修饰符,它和 protected 区别在于 protected 可以在其子类实例中访问;另外还提供了只读修饰符 readonly 和可通过类名来访问的静态属性 static 修饰符。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// es6中的class类
class Animal {

// 另外的四类属性修饰符
// protected private readonly static

public name: string;

constructor(name: string){
this.name = name
}

run(){
return `${this.name} is running`
}
}

const snake = new Animal('Lina')

console.log(snake.run())


class Dog extends Animal {
bark(){
return `${this.name} is barking`
}
}

const erha = new Dog('erha')

console.log(erha.run())

console.log(erha.bark())


class Cat extends Animal {
constructor(name){
super(name)
}
run(){
return 'Meow, ' + super.run()
}
}

const mao = new Cat('maomao')

console.log(mao.run())


// class与接口

interface Radio {
switchRadio(): void;
}

interface Battery {
checkBatteryStatus();
}

interface RadioWithBattery extends Radio{
checkBatteryStatus();
}

class Car implements Radio{
switchRadio(){
// do something
}
}

class CellPhone implements RadioWithBattery{
switchRadio(){
// do something
}
checkBatteryStatus(){
// do something
}
}