首页 前端知识 TS class类的定义、extends类的继承、属性修饰符、implements类的接口实现、abstract抽象类

TS class类的定义、extends类的继承、属性修饰符、implements类的接口实现、abstract抽象类

2024-10-26 09:10:52 前端知识 前端哥 574 702 我要收藏

TS class类的定义、extends类的继承、属性修饰符、implements类的接口实现、abstract抽象类

1. class类定义
class Person {
  // 与 js 不同,这里必须要声明所需变量,否则 constructor 中 this 无法访问到属性
  name:string
  age:number
  address:string
  
  constructor(name:string,age:number,address:string) {
    this.name = name
    this.age = age
    this.address = address
  }
}

let p1 = new Person("ccc", 22, "china")
console.log(p1)  // Person { name: 'ccc', age: 22, address: 'china' }
2. extends类继承
class Person {
  name:string
  age:number
  address:string
  constructor(name:string,age:number,address:string) {
    this.name = name
    this.age = age
    this.address = address
  }
}

// 使用 extends 继承 Person 类
class Man extends Person {
  sex:number
  constructor(name:string,age:number,address:string, sex:number) {
    super(name, age, address)
    this.sex = sex
  }
}

let p1 = new Man("ccc", 22, "china", 1)
console.log(p1)  // Man { name: 'ccc', age: 22, address: 'china', sex: 1 }
3. 属性修饰符(static、public、protected、private)
class Person {
  static s = "static"
  name1:string
  protected age:number
  private address:string
  constructor(name1:string,age:number,address:string) {
    this.name1 = name1
    this.age = age
    this.address = address
  }
  static fun() {
    // static 修饰的方法无法访问其他修饰符修饰的变量
    this.name1  // 报错
    this.s  // 可以访问
  }
}

class Man extends Person {
  sex:number
  constructor(name:string,age:number,address:string, sex:number) {
    super(name, age, address)
    this.sex = sex
    this.address  // 报错:address 为 private 私有变量
  }
}

let p1 = new Man("ccc", 22, "china", 1)

p1.s // 报错:static 修饰的变量无法在实例上访问
Person.s // 可以访问
p1.name1 // 可以访问
p1.age // 报错:protected 修饰的变量无法在实例上访问
4. implements类的接口实现
interface F {
  // 接口中只能包含抽象方法,不能有具体实现
  cName: () => void
}

class Person implements F {
  name: string
  age: number
  address: string

  constructor(name: string, age: number, address: string) {
    this.name = name
    this.age = age
    this.address = address
  }
  // 需要对 interface F 中有具体的方法实现
  cName():void {
    console.log(this.name);
  }
}

let p1 = new Person("ccc", 22, "china")
p1.cName()  // ccc
5. abstract抽象类
abstract class Person {
  name1:string
  constructor(name1:string) {
    this.name1 = name1
  }
  // 抽象方法只能在抽象类中定义
  abstract cName():void
}

let p1 = new Person("chenxize") // 报错:无法创建抽象类的实例

class Man extends Person {
  age:number
  constructor(name:string, age:number) {
    super(name)
    this.age = age
  }
  // 需要对抽象类中的抽象方法有具体实现
  cName():void {
    console.log(this.name1);
  }
}

let m1 = new Man("chenxize", 22)
console.log(m1);  // Man { name1: 'chenxize', age: 22 }

转载请注明出处或者链接地址:https://www.qianduange.cn//article/19177.html
标签
评论
发布的文章
大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!