typescript——类的定义 继承 修饰符

本文深入探讨了TypeScript中类的定义与使用,包括属性、构造函数、方法、继承及修饰符的详细解释与示例代码。通过具体案例,展示了如何创建类、实例化对象、重写父类方法以及理解公有、保护和私有修饰符的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

类的定义

class Person {
  name: string // 属性

  constructor (n: string) { // 构造函数 实例化类时候触发的方法
    this.name = n
  }

  run (): void { // 方法
    console.log((this.name))
  }
}

let p = new Person('bob')
p.run()
class Person {
  name: string

  constructor (name: string) {
    this.name = name
  }

  getName (): string {
    console.log(this.name)
    return this.name
  }

  setName (name: string): void {
    this.name = name
  }
}

let p = new Person('bob')
p.getName() // bob
p.setName('lucy')
p.getName() // lucy

继承 extends super

class Person {
  name: string

  constructor (name: string) {
    this.name = name
  }

  run (): void {
    console.log(`${this.name} is running`)
  }
}

let p = new Person('tom')
p.run() // tom is running

// 继承
class Child extends Person {
  friend: string

  constructor (name: string, friend: string) {
    super(name)
    this.friend = friend
  }

  work () {
    console.log(`${this.name} is working`)
  }

  run () { // 重写父类方法
    console.log(`${this.friend} is my best friend`)
  }
}

let p1 = new Child('lucy', 'john')
p1.run() // john is my best friend
p1.work() // lucy is working

修饰符

public:公有,在类里面、子类、类外面都可以访问
protected:保护类型,在类里面、子类里面都可以访问,在类外部无法访问
private:私有,在类里面可以访问,子类、类外部都无法访问

属性如果不加修饰符,默认就是 public

class Person {
  public name1: string
  protected name2: string
  private name3: string

  constructor (json: any) {
    this.name1 = json.name1
    this.name2 = json.name2
    this.name3 = json.name3
  }

  run (): void {
    console.log(`1-1:${this.name1} 1-2:${this.name2} 1-3:${this.name3}`)
  }
}

let p = new Person({ name1: 'bob1', name2: 'tom1', name3: 'lucy1' })
p.run() // tom is running
// console.log(p.name1, p.name2, p.name3) // name2 name3 在 typescript 中编译报错

class Child extends Person {
  constructor (json: any) {
    super(json)
  }

  run (): void {
    // name3 在 typescript 中编译报错
    console.log(`2-1:${this.name1} 2-2:${this.name2} 2-3:${this.name3}`)
  }
}

let p1 = new Child({ name1: 'bob2', name2: 'tom2', name3: 'lucy2' })
p1.run()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值