静态属性
使用static修饰,只能在类中被访问到,如代码中的grades
成员属性
使用public修饰,可省略不写,成员属性不设置默认值时,需要添加!,如name!:string,成员属性可在类中、外部访问到
私有字段
使用#修饰,不能在类以外的地方被访,如代码中的#name
class Student {
static grades: number = 7
name!: string
#name: string = 's'
age: number = 10
constructor(_name: string, _age: number) {
this.#name = _name
Student.age = _age
}
static show = () => {
return '静态方法'
}
getName() {
return this.#name
}
getAge = () => {
return this.age
}
}
const getsd = new Student('sss', 111)
console.log(getsd.age) // 111
console.log(getsd.getAge()) // 111
console.log(getsd.name) // undefined
console.log(getsd.getName()) // Student
console.log(Student.grades) // 111
console.log(Student.show()) // 静态方法
console.log(getsd.#name) // error
修饰符
static:只能在类中被访问
public:可以在类中、子类中以及外部被访问到
protected:可以在类中、子类中被访问到
网友评论