// public 定义类的变量默认就是公共的,继承的子类可以通过this来访问
// private 定义类的私有属性,只能在内部访问
class Person {
private name: string = ""
getName() {
return this.name
}
setName(newName) {
this.name = newName
}
}
const p = new Person()
console.log(p.getName())
p.setName('xbj')
// protected: 在类的内部和子类中可以访问,在外面就访问不到了
class Person {
protected name: string
constructor(name: string) {
this.name = name
}
}
class Student extends Person {
constructor(name: string, age: number){
super(name)
}
getName() {
return this.name
}
}
ts类中的成员修饰符public、private、protected
最新推荐文章于 2024-03-04 20:57:55 发布
本文介绍了JavaScript中类的访问修饰符public、private和protected的用法。public变量在类的外部可以直接访问,private属性只能在类内部访问,而protected属性则允许在类内部和子类中访问。示例展示了这些修饰符如何应用于Person和Student类的name属性。
摘要由CSDN通过智能技术生成