# 类
# 访问修饰符
默认public, 私有private, 受保护protected
class Animal {
name: string
// 只能当前类访问
private food: string
constructor(name: string, food: string) {
this.name = name
this.food = food
}
// 默认public
eat() {
console.log(`eat ${this.food}`)
}
// 只能当前类或子类访问
protected run() {
console.log('running')
}
}
class Dog extends Animal {
constructor(name: string, food: string) {
super(name, food)
}
keepRun() {
super.run()
}
}
const dog = new Dog('wangcai', 'bone')
dog.food // error
dog.eat() // eat bone
dog.run() // error
dog.keepRun() // running
# 只读修饰符
class Person {
readonly name: string = 'zhuli'
}
const p = new Person()
console.log(p.name) // zhuli
p.name = 'lisi' // error