TypeScript学习笔记(三) | 类

131 阅读2分钟

1.类的定义

class Person {
    name: string;
    constructor(n:string) {
        this.name = n;
    }
    run():void {
        console.log(this.name);
        
    }
}
let zs = new Person('zs')
zs.run() // zs

2.类的继承

class Person {
    name: string;
    constructor(n: string) {
        this.name = n;
    }
    run(): string {
        return '姓名:'+this.name;
    }
}
class Man extends Person {
    age:number;
    sex:string= '男';
    constructor(name: string, age: number) {
        super(name);
        this.age = age;
    }
    sayHi():string {
        return `姓名:${this.name};年龄:${this.age};
        性别:${this.sex};`
    }
}
var zs = new Man('曾森',18)
console.log(zs.sayHi()); // 姓名:曾森;年龄:18; 性别:男;

3.类的修饰符

有三种

  1. public
  2. protected
  3. private

默认public

①public 公有修饰符

class Other {
    public name: string;
    constructor(n: string) {
        this.name = n;
    }
    run(): string {
        return '姓名:' + this.name;
    }
}
var zs = new Other('zs22');
console.log(zs.name); // 可以访问

②protected 保护修饰符

在类里面和子类可以访问,类外不可访问

class Other {
    protected name: string;
    constructor(n: string) {
        this.name = n;
    }
    run(): string {
        return '姓名:' + this.name;
    }
}
var zs = new Other('zs22');
console.log(zs.name); // 类外不可访问

③private 私有修饰符

当前类里面可以访问,子类和类外不可访问

4.静态属性,静态方法

静态属性和静态方法

静态方法不能调用类里面的属性,只能调用静态属性

class Other {
    protected name: string;
    
    // 静态属性
    static sex = "男"; 
    
    constructor(n: string) {
        this.name = n;
    }
    run(): string {
        return '姓名:' + this.name;
    }
    
    // 静态方法
    static print() { 
    	console.log(sex); // 调用静态属性
    }
}
Other.print(); // 调用静态方法
Other.sex; // 调用静态属性

5.多态

父类定义一个方法不去实现,让子类去实现,以此实现不同子类有不同的方法。

多态属于继承。

class Animal {
    name:string;
    constructor(name:string) {
        this.name = name;
    }
    say() { // 定义一个方法不做处理
        console.log('叫声');
    }
}
class Cat extends Animal {
    constructor(name:string) {
        super(name)
    }
    say() { // 子类实现
        return this.name + 'say:喵喵';
    }
}
class Dog extends Animal {
    constructor(name:string) {
        super(name) 
    }
    say() { // 子类实现
        return this.name + 'say:汪汪'
    }
}
let xiaoM = new Cat('xiaoM'); 
let xiaoH = new Dog('xiaoH')
console.log(xiaoH.say());  // xiaoHsay:汪汪
console.log(xiaoM.say()); // xiaoMsay:喵喵

6. 抽象类和抽象方法

  1. 抽象类是提供其他类继承的基类,不能直接被实例化,如下图。 截图.png

  2. 用abstract关键字定义抽象类和抽象方法,抽象类中的抽象方法不包含具体实现并且必须在派生类(子类)中实现。

  3. 抽象方法只能放在抽象类里面。 作用:抽象类和抽象方法用来定义标准。
    例如:要求Animal这个类的子类必须包含eat()方法。

abstract class Animal {
    public name:string;
    constructor(name:string) {
        this.name = name;
    }
    // 定义抽象方法,且不包含具体实现
    abstract eat():any;  // 定义eat方法,表面子类必须要有这个方法,否则报错
}
class Dog extends Animal { 
    constructor(name:string) {
        super(name)
    }
    eat() { // 派生类(子类)中实现
        console.log(this.name); 
    }
}