TS笔记 - 03类的知识 class

TS类的知识

1.定义类

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
/*ES5 类*/
function Person(name){
this.name = name;
this.run(name){
console.log(name);
}
}
var p = new Person('张三');
p.run();

/*TS*/
class Person{
name:string;
constructor(n:string){
this.name = n;
}
run():void{
console.log(this.name);
}
}
var p = new Person('张三');
p.run();


/*TS*/
class Person{
name:string;
constructor(name:string){
this.name = name;
}
getName:string{
return this.name;
}
setName(name:string):void{
this.name = name;
}
}
var p = new Person('张三');
p.getName();
p.setName('李四');

2.实现继承 extends \ super

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Person{
name:string;
constructor(name:string){
this.name = name;
}
run:string{
return `${this.name}在运动`;
}
}
class Web extends Person{
constructor(name:string){
super(name); // 初始化父类构造函数
}
run():string{
return `${this.name}在运动 - 子类run`;
}
work():string{
return `${this.name}在运动 - 子类work`;
}
}
var w = new Web('李四');
w.run();//李四在运动 - 子类run
w.work();//李四在运动 - 子类work

3. 类修饰符

  • public 公有 在类里面 子类 外面 都可以访问
  • protected 保护类型 在类里面 子类 可以访问 类外不能访问
  • private 私有类型 在类里面可以访问 子类 类外 不能访问
  • 如果不加修饰符 默认为公有
1
2
3
4
5
6
7
8
9
class Person{
public name:string;
constructor(name:string){
this.name = name;
}
run:string{
return `${this.name}在运动`;
}
}

4.静态方法 静态属性

  • 类外部可以调用 静态属性
  • 静态方法 没发直接调用类里面的属性 this.name
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    class Person{
    public name:string;
    static sex:string = 'man';
    constructor(name:string){
    this.name = name;
    }
    run:string{ // 实例方法
    return `${this.name}在运动`;
    }
    work:string{
    return `${this.name}在工作`;
    }
    static print(){// 静态方法 没发直接调用类里面的属性 this.name
    return 'print 方法';
    }
    }
    var p = new Person('张三');
    p.run();
    Person.sex; //类外部可以调用 静态属性

5.多态 父类定义一个方法不去实现,让继承它的子类去实现 每一个子类有不同的表现

也是继承的一种

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
class Animal{
name:string;
constructor(name:string){
this.name = name;
}
eat(){ // 具体吃什么不知道 继承它的子类去实现
console.log('吃方法');
}
}
class dog extends Animal{
constructor(name:string){
super(name); // 继承
}
eat(){
return this.name + '吃狗粮'
}
}
class Cat extends Animal{
constructor(name:string){
super(name); // 继承
}
eat(){
return this.name + '吃老鼠'
}
}

6.abstract 抽象方法只能放在抽象类里面

  • 它是提供其它类继承的基类 不能直接被实例化
  • 抽象类和方法用来定义标准 Animal这个类要求它的子类必须包含eat方法
  • 用abstract关键字定义抽象类和抽象方法 抽象类中的抽象方法 不包含具体实现并且必须派生类中实现
  • 抽象类方法只能存在抽象类中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
abstract class Animal{
name:string;
constructor(name:string){
this.name = name;
}
abstract eat():any;
}
// var a = new Animal(); 错误写法
class Dog extends Animal{
constructor(name:string){
super(name); // 继承
}
//抽象类的子类必须实现抽象类里面的抽象方法
eat(){
return this.name + '吃鸡肉'
}
}
var n = new Dog('小黑');
n.eat();