【学习打卡】第52天 TypeScript(8)
2022/9/26 4:17:10
本文主要是介绍【学习打卡】第52天 TypeScript(8),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
类的静态属性
- 类的静态属性就是直接挂载到类上的属性,而不是实例或者原型上的属性
- 在ES6中使用static表示静态属性或者方法
// ES5 function Person(name:string, age: 18) { this.name = name; this.age = age; } Person.attr="move" // ES6 class Person { static attr = 'move'; constructor(public name: string, public age: number) {} } const person = new Person('tz', 18);
类的getter和setter
如下,当想获取或者修改私有属性_name时,不可以在类外修改,可以通过getter获取,通过setter修改
class Person { constructor(private _name: string) {} get name() { return this._name; } set name(val: string) { this._name = val; } } const person = new Person('tz'); console.log(person.name); // tz person.name = 'tom'; console.log(person.name); // tom
单例
class Person { private static instance: Person; private constructor() {} static getInstance() { if (!this.instance) { this.instance = new Person(); } return this.instance; } } const person = Person.getInstance();
类中的readonly
readonly只能读不能改
class Person { public readonly name: string; constructor(name: string) { this.name = name } } const person = new Person('tz'); person.name = 'tom'; // 报错: name属性只读不能改 console.log(person.name); // tz
抽象类
- 抽象类把其他类共有的属性或者方法抽离出来,用abstract来表示
- 抽象类不可以实例化,只能被继承
- 抽象类中也可以有具体属性或者方法的实现
abstract class Geom { constructor(public width: string){} getType() { return "Geom"; } abstract getArea(): number; } class Circle extends Geom{ getArea(): number { return 123; } } class Square{ getArea(): number { return 456; } }
这篇关于【学习打卡】第52天 TypeScript(8)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-04-16软路由代理问题, tg 无法代理问题-icode9专业技术文章分享
- 2024-04-16程序猿用什么锅-icode9专业技术文章分享
- 2024-04-16自建 NAS 的方案-icode9专业技术文章分享
- 2024-04-14ansible 在远程主机上执行脚本,并传入参数-icode9专业技术文章分享
- 2024-04-14ansible 在远程主机上执行脚本,并传入参数, 加上remote_src: yes 配置-icode9专业技术文章分享
- 2024-04-14ansible 检测远程主机的8080端口,如果关闭,则echo 进程已关闭-icode9专业技术文章分享
- 2024-04-14result 成功怎么写-icode9专业技术文章分享
- 2024-04-14stopped 状态设置为变量,由外部传递进来-icode9专业技术文章分享
- 2024-04-14为什么ansible执行远程脚本需要放到后台-icode9专业技术文章分享
- 2024-04-14shell 正则判断字符串内是否含有th-icode9专业技术文章分享