ES6提供了更接近传统语法的写法,引入class类,作为对象的模板。通过class关键字,可以定义类。
// 定义类
class Person {
constructor() {
}
run () {
}
}
1. TS定义class类
class Person {
name: string
age: number
constructor(name: string, age: number) {
this.name = name
this.age = age
}
run() {
}
}
恭喜你已经学会了在class中 如何定义变量
2. 类的修饰符
总共有三个 public private protected
使用public 修饰符 可以让你定义的变量 内部访问 也可以外部访问 如果不写默认就是public
使用 private 修饰符 代表定义的变量私有的只能在内部访问 不能在外部访问
使用 protected 修饰符 代表定义的变量私有的只能在内部和继承的子类中访问 不能在外部访问
代码:
class Person {
public name: string
private age: number
protected some: any
constructor(name: string, age: number, some: any) {
this.name = name
this.age = age
this.some = some
}
run () {
}
}
class Man extends Person {
constructor() {
super('张三', 18, 1)
console.log(this.some)
}
create() {
console.log(this.some)
}
}
let xx = new Person('漳卅', 12, 2)
let man = new Man()
man.some
3. static 静态属性 和 静态方法
我们用static 定义的属性 不可以通过this 去访问 只能通过类名去调用
static 静态函数 同样也是不能通过this 去调用 也是通过类名去调用
需注意: 如果两个函数都是static 静态的是可以通过this互相调用
4.interface 定义 类
ts interface 定义类 使用关键字 implements 后面跟interface的名字多个用逗号进行隔开 继承还是用extends
interface PersonClass {
get(type: boolean): boolean
}
interface PersonClass2 {
set(): void,
msg: string
}
class A {
name: string,
constructor() {
this.name = '123'
}
}
class Person extends A implements PersonClass, PersonClass2 {
msg: string,
constructor() {
super()
this.msg = '123'
}
get(type: boolean) {
return type
}
set() {
}
}