Appearance
三要素:继承 封装 多态
- 继承,子类继承父类
- 封装,数据的权限和保密
- 多态,同一接口不同实现
继承
- People 是父类,公共的,不仅仅服务于 Student
- 继承可将公共方法抽离出来,提高复用,减少冗余
javascript
// 子继承父类
class Student extends People {
constructor(name, age, number) {
super(name, age);
this.number = number;
}
study() {
alert(`${this.name} study`);
}
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
javascript
// 实例
let xiaoming = new Student('xiaoming', 10, 'A1')
xiaoming.study()
console.log(xiaoming.number)
xiaoming.eat()
let xiaohong = new Student ('xiaohong', 11,'A2')
xiaohong.study()
xiaohong.speak()
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
封装
概念
- 减少耦合,不该外露的不外露
- 利于数据、接口的权限管理
- ES6 目前不支持,一般认为_开头的属性是 private
ts 语法
- public 完全开放
- protected 对子类开放
- private 对自己开放
typescript
class People {
name
age
protected weight // 受保护的属性,只有自己或者子类可以访问
constructor(name, age) {
this.name = name;
this.age = age;
this.weight = 120
}
eat() {
alert(`${this.name} eat something `);
}
speak() {
alert(`My name is ${this.namel} age ${this.age}!`);
}
}
// 子继承父类
class Student extends People {
number
private girfriend // 定义私有的
constructor(name, age, number) {
super(name, age);
this.number = number;
this.girfriend = 'xiaoli'
}
getWeight() {
alert(`weight ${this.weight}`);
}
}
// 实例
let xiaoming = new Student('xiaoming',10,'A1')
xiaoming.getWeight();
conslog.log(xiaoming.girfriend) // 注意这时候会报错,编译不通过
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
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
多态
- 同一个接口,不同表现
- JS 应用极少
- 需要结合 java 等语言的接口、重写、重载等功能
- 保持子类的开放性和灵活性
- 面向接口编程
javascript
class People {
constructor(name) {
this.name = name
}
saySomething() {
}
}
class A extends People {
constructor(name) {
super(name)
}
saySomething() {
alert('I am A')
}
}
class B extends People {
constructor(name) {
super(name)
}
saySomething() {
alert('I am B')
}
}
let a = new A('a')
a.saySomething()
let b = new B('b')
b.saySomething()
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
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