四、类

# 四、类
# 类的继承和成员修饰符
/**
* 修饰符
* 公共:public
* 私有化:private
* 被保护:protected
* 只读:readonly
* 静态:static
*/
class Dog {
constructor(name: string) {
this.name = name
}
// 公共
public name: string
run() {}
// 私有化
private pri() {}
// 被保护: 被保护的类,不能被声明实例化,只能被继承
protected pro() {}
// 只读: 只能读取,不能被修改,只读属性初始化的时候一定有默认值
readonly legs: number = 4
// 静态:类的静态成员,只能通过类名来调用,而不能通过子代调用,类的静态成员也可以被继承
static food: string = 'bones'
}
console.log(Dog.prototype)
let dog = new Dog('wangwang')
console.log(dog)
console.log(Dog.food)
// console.log(dog.foot)
// dog.pri()
// dog.pri()
// 内部属性只在实例上,不在原型上
// 与es不同,实例属性必选有初始值,或者在构造函数中被初始化
// 除了类的成员可以添加修饰符外,构造函数的参数也可以添加修饰符,作用是将参数自动变为实例属性,可以省略函数内部的定义
class Husky extends Dog {
constructor (name: string, public color: string) {
super(name)
this.color = color;
// this.pri()
this.pro()
}
// color: string
}
console.log(Husky.food)
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
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
# 抽象类与多态
/**
* 抽象类与多态
* 抽象类(abstract): 抽象类无法实例化,只能被继承
* 抽象方法:在抽象类中,定义一个方法,不具体实现。好处是在父类声明,子类实现
* 抽象类的好处:抽离出一些事物的共性,有利于代码的复用与扩展,抽象类也可以实现多态
*
* 多态:在父类声明抽象方法,在多个子类不同的实现。
* 在程序运行时,会根据不同的对象,对应不同的方法,执行不同的操作,这样就实现运行时的绑定
*
*/
abstract class Animal {
eat() {
console.log('eat')
}
// 抽象方法
abstract sleep(): void
}
class Cat extends Animal {
constructor(name: string) {
super()
this.name = name
}
name: string
run() {}
sleep() {
console.log('cat sleep')
}
}
// 抽象类无法实例化,只能被继承
// let animal = new Animal()
let cat = new Cat('miao')
cat.eat();
class Tiger extends Animal {
sleep() {
console.log('tiger sleep')
}
}
let tiger = new Tiger();
let animals: Animal[] = [cat, tiger]
animals.forEach(i => {
i.sleep()
})
// this类型的作用
class WorkFlow {
step1() {
return this;
}
step2() {
return this;
}
}
// this 方法的链式调用
new WorkFlow().step1().step2()
class Myflow extends WorkFlow {
next() {
return this;
}
}
// 这样就可以保持父类与子类接口调用的连贯性
new Myflow().next().step1().next().step2()
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
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
上次更新: 2021/04/22, 00:08:06