Appearance
ts
class Person {
// 表示实例上有这个属性,可以省略 public
// ! 表示非空断言,解决初始化时没有传值的问题,另一种解决方式是关闭严格模式。
name!: string
public age: number
x: number = 10
constructor (name: string, age: number) { // 其实就是函数的参数
this.name = name
this.age = age
}
}
const p = new Person('foo', 18)ts
class Foo {
// name: string
// constructor (name) {
// this.name = name
// }
// 等价于上面
constructor (public: name: stirng) {
this.name = name
}
}类的修饰符
ts
class Person {
// public 表示父类本身、子类、类外面都可以获取的属性
// protected 表示父类本身、子类可以访问, 类外面不可以访问。
// private 表示只有父类本身能访问到
// readonly 表示只读属性,类似于 const,在构造器中可以多次赋值,
// 构造器外不能再修改引用
public name!: string
protected readonly age!: number
// 构造函数前也可以加修饰符
// 如果用 protected 或 private 修饰,就不能 new 了。
// 如果用 private 修饰,子类就不能继承了。
constructor (name: string, age: number) { // 其实就是函数的参数
this.name = name
this.age = age
}
}
class Student extends Person {
school: string
constructor (name: string, age: number, school: string) {
super(name, age)
this.school = school
}
}静态属性和静态方法
通过类来调用的属性和方法就是静态属性和静态方法(是可以被继承的)
ts
class Foo {
static bar = 'bar'
static baz = () => {}
say () {}
}
Foo.bar
Foo.baz()
class X extend Foo {
// 子类重写父类的方法
static baz = () => {
// 静态方法中的 super 指的也是父类
super.baz() // 调用父类的 baz
}
say () {
// 原型上方法的 super 指的是父类的原型 Foo.prototype
super.say()
}
// 属性访问器
get eat () {
return 'eat'
}
}
x.bar
x.baz()类既可以当成类型,也可以当成值。
ts
class Foo {
}
let foo = Foo
let bar: typeof Foo = Foo
function baz (cls: new () => Foo) {}
baz(Foo)