Typescript中的类
- Public:修饰的属性或方法是共有的
- Private:修饰的属性或方法是私有的
- Protected:修饰的属性或方法是受保护的
- TS提供了一个只读属性readonly,在变量前面声明,则变量只读而不能修改
//定义一个类
class Animal {
readonly name:string;
constructor(name:string){
this.name = name
}
protected eat(){
//保护方法,在实例中不能使用,子类中可用
return `${this.name} is eatting`
}
private run(){
//私有方法,只能在类中使用
return `${this.name} is running`
}
}
//创建Animal的实例snake
const snake = new Animal('snake')
snake.name = 'snake' //报错:无法分配到 "name" ,因为它是只读属性。
console.log(snake.eat()) //snake is eatting //报错:属性“eat”受保护,只能在类“Animal”及其子类中访问。
console.log(snake.run()) //报错:属性“run”为私有属性,只能在类“Animal”中访问
//创建子类Cat
//把private run()方法注释掉,因为是私有的,所以子类也不能继承
//但是protected eat()方法仍能继承
class Cat extends Animal {
constructor(name) {
//ES6 要求,子类的构造函数必须执行一次 super() 函数
//super 作为函数调用时,内部的 this 指的是子类实例
super(name)
console.log(this.name);
}
eat() {
//使用父类方法,也需要用super
return super.eat() + ' fast'
}
}
const mimi = new Cat('mimi')
mimi.name = 'newMimi' //报错:无法分配到 "name" ,因为它是只读属性。
console.log(mimi.run()); //mimi is eatting fast //没有报错
类和接口
面向对象中,一个类只能继承于另一个类,如果不同的类有相同的特性,使用子类继承父类的话很难完成,此时可以把相同的特性提取成接口,用implements来实现
- 例子:汽车和手机两个类都有共同的打开收音机方法,但是使用子类继承父类来提取方法,就很取决哪个类是父类哪个是子类
class Car {
switchRadio(trigger:boolean){
}
}
class CellPhone {
switchRadio(trigger:boolean){
}
}
此时把可以switchRadio抽取成一个接口,如果需要多个结果,需要用’,'来继承多个接口
//Car和CellPhone共有Radio
interface Radio{
//需要用":"来表达返回结果,void表示什么都不返回
switchRadio(trigger:boolean):void
}
//CellPhone特有Battery
interface Battery{
checkBattery(trigger:boolean):void
}
//用一个接口来继承另一个接口
interface radioWithBattery extends Radio{
//Radio已经有switchRadio,额外定义一个checkBattery
checkBattery(trigger:boolean):void
}
//此时类要使用implements来实现
class Car implements Radio{
switchRadio(trigger:boolean){
}
}
//多个接口的继承用","隔开
class CellPhone implements Radio,Battery{
switchRadio(trigger:boolean){
}
checkBattery(){}
}
//功能同上
class NewPhone implements radioWithBattery {
switchRadio(trigger:boolean){
}
checkBattery(){}
}
枚举 Enums
在一定范围内的一系列常量,例如一周七天,上下左右等
enum Direction {
//如果不赋值,则会从0开始递增
//如果第一项赋值为数字,则从第一项数字递增up=10,则down=11...
up, //0
down, //1
left, //2
right //3
}
//可以使用点语法来取值
//如果没有赋值或已经赋值而且为数字,则可以使用[值]来反向取key值,但如果赋值为字符串,则为undefined
console.log(Direction[0]); //"up"
console.log(Direction.up); // 0
-
常量枚举
提升性能 const enum
编译之后js文件只编译结果不编译枚举代码 -
计算枚举(待补充)