类的成员修饰符
在TypeScript中,类的属性和方法支持三种修饰符: public、private、protected。
- public 修饰的是在任何地方可见、公有的属性或方法,默认编写的属性就是public的
- private 修饰的是仅在同一类中可见、私有的属性或方法
- protected 修饰的是仅在类自身及子类中可见、受保护的属性或方法
public是默认的修饰符,也是可以直接访问的,我们这里来演示一下protected和private。
class Person {
protected name: string
constructor(name: string) {
this.name = name
}
}
class Student extends Person {
constructor(name: string) {
super(name)
}
running() {
console.log(this.name + " running")
}
}
class Person {
private name: string
constructor(name: string) {
this.name = name
}
}
const p = new Person("haha")
console.log(p.name)
只读属性readonly
如果有一个属性我们不希望外界可以任意的修改,只希望确定值后直接使用,那么可以使用readonly。
class Person {
readonly name: string
constructor(name: string) {
this.name = name
}
}
const p = new Person("haha")
console.log(p.name)
p.name = 'xixi'
getters/setters
在前面一些私有属性我们是不能直接访问的,或者某些属性我们想要监听它的获取(getter)和设置(setter)的过程,这个时候我们可以使用存取器。
class Person {
private _name: string
set name(newName) {
this._name = newName
}
get name() {
return this._name
}
constructor(name: string) {
this.name = name
}
}
const p = new Person("haha")
p.name = "xixi"
console.log(p.name)
参数属性
TypeScript 提供了特殊的语法,可以把一个构造函数参数转成一个同名同值的类属性。这些就被称为参数属性。
class Person {
constructor(public name: string, private _age: number) {
}
set age(newAge){
this._age = newAge
}
get age() {
return this._age
}
}