请教老师关于类的问题,谢谢。

来源:5-8 Class类(修饰符、构建函数、接口扩展)

LinkeZ

2023-04-07

class Proson {
  public name: string = 'linke'
  getName() {
    return this.name
  }
}


class Proson1 extends Proson {
  name1: string = 'linkeZ'
  constructor() {
    super()
    console.log(super.name) 
    console.log(this.name1)
  }
}

const proson1 = new Proson1()

结果为:

undefined
linkeZ

请教老师,在子类中使用console.log(super.name)控制台打印出的是undefined,父类中的name使用public还是protected都是一样的结果,这是为什么呢?这样的话这两个修饰符的意义是什么呢?
我的TypeScript版本是"^5.0.3"。

写回答

1回答

Brian

2023-04-11

你不能直接打印申明的成员啊,你要打印需要getName,或者this.name方法,console.log(this.name)这样就可以了。

父类中的name使用public还是protected都是一样的结果,这是为什么呢?

——如果你希望在子类中访问父类的 name 成员,可以在 Proson1 类中直接使用 this.name,因为 name 在父类中被声明为 public,可以在子类中直接继承和访问。


另外:

public、protected 和 private 三种访问修饰符进行修饰,用于控制类成员在类内部和类外部的可见性和可访问性。

public内外都可访问,protected,内部子类中可访问,外部不可访问,private只有自己可访问。


0
2
Brian
回复
LinkeZ
应该的,不谢
2023-06-05
共2条回复

NestJS 入门到实战 前端必学服务端新趋势

近几年快速发展的Node.js框架,掌握未来前端工程师后端开发能力

569 学习 · 238 问题

查看课程