ts类的使用
1、抽象类
情况:用于实现同一种目的,比如要计算面积,而三角形、圆形、梯形的求面积方式不同,但是知道是需要有求面积的方法,就需要一个抽象类求面积
点击查看代码
// 抽象类
abstract class Animal {
abstract makeSound():void
move():void{
console.log('Moving');
}
}
// 抽象类不可以实例化
// const animal = new Animal(); //error
// 通常都是通过继承抽象父类,对子类进行实例化
class Dog extends Animal{
//实现父类的抽象方法
makeSound(): void {
console.log('Wang')
}
}
const dog = new Dog();
// 此处调用的依然是Dog类的makeSound方法,Dog类是不能继承父类的抽象方法的
dog.makeSound();
dog.move();
2、访问限定符:public、private、protected
点击查看代码
class Car {
//不加public修饰符,表示默认属于public可被外界访问的
public run1() {
console.log('running1')
//class内部访问
this.run2() //ok
this.run3(); //ok
}
//private修饰符规定被修饰的成员只能被class自己内部访问
private run2() {
console.log('running2')
}
//protected修饰符修饰的成员只能被class自己内部及子类的内部访问
protected run3() {
console.log('running3');
}
}
//继承父类Car
class GTR extends Car{
init() {
//子类可以调用父类protected修饰的成员
this.run3();
}
}
const car = new Car();
car.run1();
const gtr = new GTR();
gtr.init();
// car.run2(); //error
注意:
(1)当成员被设置为 protected 之后, 被此限定符修饰的成员是只可以被类的内部以及类的子类访问。
(2)当成员被设置为 private 之后, 被此限定符修饰的成员是只可以被类的内部访问。
(3)成员都默认为 public, 被此限定符修饰的成员是可以被外部访问。
3、class内的readonly成员
点击查看代码
class Octopus {
readonly name: string
// 一:只读属性在属性声明的时候可对属性进行初始化
readonly numberOfLegs: number = 8;
//二:只读属性在构造函数内初始化只读属性
constructor(paramsName: string) {
this.name = paramsName;
}
}
const octopus = new Octopus('mao');
console.log(octopus.name); //mao
//只读属性不可修改
// octopus.name = 'ding'; //error
4、属性存取器
通过getters/setters来截取对对象成员的访问
点击查看代码
// 我们先检查用户密码是否正确,然后再允许其修改员工信息。 我们把对 `fullName`的直接访问改成了可以检查密码的 `set`方法。
// 我们也加了一个 `get`方法,让上面的例子仍然可以工作。
const pwd = '12345';
//做到很好的去保护私有属性不被污染
class Employee {
private _fullName: string = 'mao'
get fullName() {
return this._fullName;
}
set fullName(newName: string){
if (pwd && pwd === '12345') {
this._fullName = newName;
} else {
console.log('请输入正确的密码');
}
}
}
const employee = new Employee();
employee.fullName = 'ding';
console.log(employee.fullName); //ding
5、class 可以作为接口使用
class 作为 interface 使用,在 React 工程中是很常用的,情况:作为接口和设置初始值两个作用,方便统一管理,减少了代码量。
点击查看代码
// 使用class作为接口
//方便统一管理
class Props {
// 方便定义初始值
public speed: number = 500
public isAuto:boolean = true
public beforeCreate:() => {}
public created: void
public name:string = 'mao'
}
class Component {
// 可直接作为接口传入到class内部,简化了代码量
public defaultProps = new Props();
constructor() {
const { speed } = this.defaultProps;
console.log(speed); // 500
}
}
const com = new Component();
浙公网安备 33010602011771号