TS语法(三)面向对象

91 阅读2分钟

类 class

使用 class 关键词来定义一个类,

  • 在类的内部声明类的属性,
  • 类有构造函数constructor,构造函数不需要返回值,默认返回当前类的实例
  • 类中可以有自己的函数,称为方法
  • 类的属性和方法支持3种修饰符,public、protected、private
    public: 默认修饰符,任何地方可见
    protected:在类自身及子类中可见
    private:仅在同一个类中可见
  • readonly:只读属性,外界不能修改被修饰的属性值
  • extends实现继承,子类使用super来访问父类
  • getters/setters
    类中的私有属性不能直接访问,或者想要监听某些属性的获取和设置过程时就用存取器。
class Person {
// 成员属性
 protected name:string;
 private age:number;
 
 readonly sex:number

 constructor(name:string,age:number,sex:number){
    this.name = name;
    this.age = age;
    this.sex = sex;
 }

 running(){
    console.log(this.name + "running")
 }

 eating(){
    console.log(this.name + "eating")
 }
}

const p1 = new Person('hh',18,0)
p1.running()
console.log(p1.name,p1.age)

// p1.sex = 1; //不能修改


class Student extends Person {
    sno:string;
    constructor(name:string,age:number,sex:number,sno:string){
        super(name,age,sex)
        this.sno = sno
    }

    studying(){
        console.log(this.name + "studying")
    }
}

image.png 报错的原因是name和age不能用在类外面,p1是创建的实例,不能访问protected和private的成员属性

getters/setters

class Person {
  // 私有属性: 属性前面一般都会使用_
  private _name: string
  private _age: number

  constructor(name: string, age: number) {
    this._name = name
    this._age = age
  }

  running() {
    console.log("running:", this._name)
  }

  set name(newValue: string) {
    this._name = newValue
  }

  get name() {
    return this._name
  }

  set age(newValue: number) {
    if (newValue >= 0 && newValue < 200) {
      this._age = newValue
    }
  }

  get age() {
    return this._age
  }
}

const p1 = new Person("hhh", 18)
p1.name = "hhh"
console.log(p1.name)

抽象类 Abstract Class

  • 抽象类使用abstract声明的类
  • 抽象类是不能被实例的,也就是说不能使用new创建实例
  • 抽象方法是只有声明没有实现体,由子类实现的
  • 抽象方法必须出现在抽象类中
abstract class Shape {
  abstract getArea()
}

class Circle extends Shape {
  constructor(public radius: number) {
    super()
  }

  getArea() {
    return this.radius ** 2 * Math.PI
  }
}

接口 interface

  • 继承:和类一样,使用 extends 进行继承
  • 接口的继承支持多继承,类不行
  • 实现:接口定义后,可以被类实现
interface Swim{
    swimming: () => void
}

interface Run{
    running: () => void
}

class Person implements Swim,Run{
    swimming(){
        console.log('swimming')
    }
    
    running(){
        console.log('running')
    }
}

枚举类型

  • 使用 enum 声明的一组常量,常量可以是数字,字符串类型
  • 枚举类型默认是有值的,如果没有指定值,默认是从0开始自增的
  • 如果指定了值,那就从该值开始自增
  • 也可以指定字符串
enum Direction {
    LEFT,
    RIGHT,
    TOP,
    BOTTOM
}

enum Direction1 {
    LEFT = 100,
    RIGHT,
    TOP,
    BOTTOM
}

enum Direction2 {
    LEFT,
    RIGHT,
    TOP = "TOP",
    BOTTOM = 3  //如果上面的TOP被赋值了,那么BOTTOM一定要初始化
}

console.log(Direction)
console.log(Direction1)
console.log(Direction2)

运行结果 image.png