- 类定义
class Person {
private name: string
age: number
constructor(name: string, age: number) {
this.name = name
this.age = age
}
display(): void {
console.log(this.name + ' ' + this.age.toString());
}
}
let p: Person = new Person("hamusuta", 20)
p.display()
- private,public,protected修饰可访问性,不写默认public
- constructor,构造函数,使用new关键字创建对象
- this.name需要提前在类中声明属性
- static,静态属性
- 静态方法中无法调用实例属性和实例方法
- 实现接口
interface Action {
run(): void
}
class Animal implements Action {
run(): void {
console.log("animal run");
}
}
class Human implements Action {
run(): void {
console.log("human run");
}
}
let a = new Animal()
let b = new Human()
a.run()
b.run()