ts中的类
用类的的方式,ts让我们有了面对想的方式进行编程
视频教程地址
下面看一个使用类的例子
class lee{
title:string
author:string
constructor(title: string) {
this.title = title;
}
}
let l=new lee('乐编码')
console.log(l)
运行结果:lee { title: '乐编码' }
我们创建了一个类,并对类进行了初始化操作
我们知道类有三大特性:
- 多态
- 继承
- 封装
继承
class editor extends lee{
write(){
console.log(this.title)
}
}
let e=new editor('乐编码')
e.write()
运行结果:乐编码
封装
提到封装我们需要记住三个关键字 public
、readonly
和 protected
。
- public表示是公开的,类的属性和方法可以在类外修改和访问的,在子类是可以继承的
- protected 是受保护的,在类外面是可修改和访问的,在子类里是可以继承和修的
- private 是私有的,所不可以在类外面访问
- readonly 是只读的,只能读取,不能修改.只读属性必须在声明时或构造函数里被初始化
class lee {
protected title: string
author: string
private age: number = 1
readonly description: string = '快乐编码,快乐生活!'
constructor(title: string) {
this.title = title;
}
}
class editor extends lee {
write() {
console.log(this.title)
console.log(this.description)
}
}
let e = new editor('乐编码')
// e.description='111' // 因为是只读的,说以这样里是错误的
// e.age 因为是私有的,所以不可以在类外面访问
e.write()
get和set
class lee {
private _title: string
get title(): string {
return this._title
}
set title(title: string) {
this._title = title
}
}
let l = new lee()
l.title = '乐编码'
console.log(l.title)
运行结果 乐编码
多态
多态一般是通过接口实现的
interface user {
title: string
say(): void
}
class hanyun implements user {
title: string = '乐编码'
say(): void {
console.log(this.title)
}
}
class tom implements user {
title: string = 'tom'
say(): void {
console.log(this.title)
}
}
let u: user
u = new hanyun()
u.say()
u = new tom()
u.say()
我们定义了一个接口 lee,然后用两个类分别实现了接口的方法和属性
接口是一种锲约,定义了,继承的类就一定要实现
let u: user
u = new hanyun()
u.say()
u = new tom()
u.say()
运行结果
乐编码
tom
静态属性
静态属性是通过static关键标识的
class lee {
static title: string = '乐编码'
}
console.log(lee.title)
类中的静态属性直接通过 类名.属性名
调用
抽象类
抽象类是通过abstract关键词声明的,抽象类中的方法也可以通过abstract声明为抽象方法,抽象方法必须在子类中实现
abstract class user { title: string abstract say(): string hi(): void { console.log('hi') }}class lee extends user { title: string = '乐编码' say(): string { return this.title }}let l = new lee()console.log(l.say())l.hi()
运行结果:
乐编码hi
和接口不同,抽象类中可以有实现,例如:例子中的hi方法,就是在抽象类中,但是子类依旧可以调用
构造函数
ts中的构造函数是通过 constructor
关键字声明的
class lee { private _title: string constructor(title: string) { this._title = title } set title(title: string) { this._title = title } get title(): string { return this._title } sayTitle(): void { console.log(this._title) }}let l = new lee('乐编码')l.sayTitle()l.title = '哈哈哈哈'l.sayTitle()
运行结果
乐编码哈哈哈哈
构造函数主要用在对内部属性的初始化的时候调用