TypeScript学习笔记之类
TypeScript的类,简单地定义如下:
class Person {
x: number; // 默认为public类型
y: number;
constructor(x1: number, y1: number) { // 默认为public类型
this.x = x1;
this.y = y1;
}
}
let test = new Person(12, 34)
ts中,定义一个类使用class关键字,使用new进行类的实例化,constructor关键字用来定义该类的构造函数。
参数属性
什么叫做参数属性,比如上面的x、y字段的声明和构造实例化是分两步进行的,可以归纳到如下一步:
class Person {
constructor(public x1: number, public y1: number) {} // 注意这里的实现
}
let test = new Person(12, 34)
继承
使用extends关键字可以实现类之间的继承,包括字段、方法的继承,看个例子:
class Person {
constructor(public x1: number, public y1: number) { }
greet() {
return this.x1 + '-' + this.y1;
}
}
class A extends Person {
constructor(x: number, y: number) {
super(x, y);
// ...
}
greet2() {
return this.greet()
}
}
let test = new A(12, 23);
console.log('extends from Person: ', test.greet()); // extends from Person: 12-23
console.log('self method: ', test.greet2()); // self method: 12-23
注意:
派生类包含了一个构造函数,它必须调用 super(),它会执行基类的构造函数。而且,在构造函数里访问 this的属性之前,我们一定要调用 super()。 这个是TypeScript强制执行的一条重要规则。
当然,调用super之后在A类中你可以像Person类中那样进行后续处理。
public修饰符
public修饰符可以表示字段或者方法是共有的,也就是说在子类和其它类是可访问的,如下:
class Animal {
public name: string;
public constructor(theName: string) { this.name = theName; }
public move(distanceInMeters: number) {
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
}
let animal = new Animal('rabbit 兔子');
animal.move(1); // rabbit 兔子 moved 1m.
animal.name = '狗熊,忘了英文咋写了';
animal.move(200); // 狗熊,忘了英文咋写了 moved 200m.
private修饰符
private修饰符可以表示字段或者方法是私有的,也就是只在当前类中有效,出了该类是无法访问的,举个栗子:
class Animal {
private name: string;
constructor(theName: string) { this.name = theName; }
}
class Rhino extends Animal {
constructor(public age: number) { super("Rhino"); }
}
let test = new Animal('狗娃');
// test.name // wrong!访问不到,因为name私有
let test2 = new Rhino(23);
test2.age // 23
protected修饰符
用protected修饰的字段只能在当前类及其子类中访问,被protected修饰的构造函数,构造函数所在的类不能直接直接进行new操作,但是该构造可以被子类继承,从而子类进行重新构造,但是还要首先调用super。
class Person {
protected name: string;
protected constructor(theName: string) { this.name = theName; }
}
// Employee 能够继承 Person
class Employee extends Person {
private department: string;
constructor(name: string, department: string) {
super(name);
this.department = department;
}
public getElevatorPitch() {
return `Hello, my name is ${this.name} and I work in ${this.department}.`;
}
}
let howard = new Employee("Howard", "Sales");
// let john = new Person("John"); // 错误: 'Person' 的构造函数是被保护的.可以被继承,不能直接new
readonly修饰符
被readonly修饰的字段是只读的,该地段必须要么在声明时初始化,要么在构造里面初始化。
class Octopus {
readonly name: string;
readonly numberOfLegs: number = 8;
constructor (theName: string) {
this.name = theName;
}
}
let dad = new Octopus("Man with the 8 strong legs");
dad.name = "Man with the 3-piece suit"; // 错误! name 是只读的.
get和set存取器
对于private字段,一般我们会在class中使用存取器进行赋值及调用,这就是get和set的作用。
class Person {
private _name: string;
set name(theName: string) {
console.log('-----------')
this._name = theName;
}
get name(): string {
return this._name + '********';
}
}
let test = new Person();
test.name = 'admin'
console.log(test.name)
输出如下:
-----------
admin********
注意:
get存取器必须要有返回值,没有返回值可以写void返回,返回不确定可以使用any类型。
静态属性
静态属性定义时,直接在属性或字段前面加上static修饰即可。
class Grid {
static origin = { x: 0, y: 0 };
static test;
constructor (public scale: number) { }
calculateDistanceFromOrigin(point: { x: number; y: number; }) {
let xDist = (point.x - Grid.origin.x);
let yDist = (point.y - Grid.origin.y);
return Math.sqrt(xDist * xDist + yDist * yDist) / this.scale;
}
testValue() {
console.log('testing: ', Grid.test);
}
}
let grid1 = new Grid(1.0); // 1x scale
let grid2 = new Grid(5.0); // 5x scale
console.log(grid1.calculateDistanceFromOrigin({x: 10, y: 10})); // 14.142135623730951
console.log(grid2.calculateDistanceFromOrigin({ x: 10, y: 10 })); // 2.8284271247461903
console.log(grid1.testValue()); // testing: undefined
注意:
static字段调用的时候直接使用:类名.字段名 调用,实例字段使用:(new Class).字段名 调用,当然class内部直接使用this调用。
抽象类
使用abstract关键字修饰一个抽象类,和接口不同的是,抽象类中可以有成员的实现细节,举个栗子:
abstract class Department {
constructor(public name: string) {
}
printName(): void {
console.log('Department name: ' + this.name);
}
abstract printMeeting(): void; // 必须在派生类中实现
}
class AccountingDepartment extends Department {
constructor() {
super('Accounting and Auditing'); // 在派生类的构造函数中必须调用 super()
}
printMeeting(): void {
console.log('The Accounting Department meets each Monday at 10am.');
}
generateReports(): void {
console.log('Generating accounting reports...');
}
}
let department: Department; // 允许创建一个对抽象类型的引用
// department = new Department(); // 错误: 不能创建一个抽象类的实例
department = new AccountingDepartment(); // 允许对一个抽象子类进行实例化和赋值
department.printName();
department.printMeeting();
// department.generateReports(); // 错误: 方法在声明的抽象类中不存在
let accountingDepartment: AccountingDepartment;
accountingDepartment = new AccountingDepartment();
accountingDepartment.generateReports();
注意:
1、abstract的class不能直接被new,只能被extends
2、abstract的method必须被子类实现
TypeScript学习笔记之类的更多相关文章
- Typescript 学习笔记七:泛型
中文网:https://www.tslang.cn/ 官网:http://www.typescriptlang.org/ 目录: Typescript 学习笔记一:介绍.安装.编译 Typescrip ...
- Typescript 学习笔记六:接口
中文网:https://www.tslang.cn/ 官网:http://www.typescriptlang.org/ 目录: Typescript 学习笔记一:介绍.安装.编译 Typescrip ...
- Typescript 学习笔记五:类
中文网:https://www.tslang.cn/ 官网:http://www.typescriptlang.org/ 目录: Typescript 学习笔记一:介绍.安装.编译 Typescrip ...
- Typescript 学习笔记四:回忆ES5 中的类
中文网:https://www.tslang.cn/ 官网:http://www.typescriptlang.org/ 目录: Typescript 学习笔记一:介绍.安装.编译 Typescrip ...
- Typescript 学习笔记二:数据类型
中文网:https://www.tslang.cn/ 官网:http://www.typescriptlang.org/ 目录: Typescript 学习笔记一:介绍.安装.编译 Typescrip ...
- Typescript 学习笔记三:函数
中文网:https://www.tslang.cn/ 官网:http://www.typescriptlang.org/ 目录: Typescript 学习笔记一:介绍.安装.编译 Typescrip ...
- Typescript 学习笔记一:介绍、安装、编译
前言 整理了一下 Typescript 的学习笔记,方便后期遗忘某个知识点的时候,快速回忆. 为了避免凌乱,用 gitbook 结合 marketdown 整理的. github地址是:ts-gitb ...
- TypeScript学习笔记(八):1.5版本之后的模块和命名空间
我之前有写过TS1.5版本之前的“模块”的笔记:TypeScript学习笔记(七):模块 但是TS这里的模块和在ECMAScript 2015里的模块(即JS原生支持了模块的概念)概率出现了混淆,所以 ...
- typescript学习笔记(三)---接口
关于第二章的学习笔记是变量声明. 接口:TypeScript的核心原则之一是对值所具有的结构进行类型检查. 它有时被称做“鸭式辨型法”或“结构性子类型化”. 在TypeScript里,接口的作用就是为 ...
- typescript学习笔记(一)---基础变量类型
作为一个前端开发者,学习新技术跟紧大趋势是必不可少的.随着2019年TS的大火,我打算利用一个月的时间学习这门语言.接下来的几篇文章是我学习TS的学习笔记,其中也会掺杂一些学习心得.话不多说,先从基础 ...
随机推荐
- PHP通过Zabbix API获取服务器监控信息
开源监控系统Zabbix提供了丰富的API,供第三方系统调用. 基本步骤如下: 1.获取合法认证:连接对应Zabbix URL,并提供用户名和密码,HTTP方法为"POST",HT ...
- Android音视频通话过程中最小化成悬浮框的实现(类似Android8.0画中画效果)
关于音视频通话过程中最小化成悬浮框这个功能的实现,网络上类似的文章很多,但是好像还没看到解释的较为清晰的,这里因为项目需要实现了这样的一个功能,今天我把它记录下来,一方面为了以后用到便于自己查阅,一方 ...
- 使用ztree展示树形菜单结构
官网:http://www.treejs.cn/v3/main.php#_zTreeInfo 一.功能简介 在权限系统中,实现给角色指定菜单权限的功能.主要包括以下几点: 读取全部菜单项,并以树形结构 ...
- (译)学习JavaScript闭包
原文地址:https://medium.freecodecamp.org/lets-learn-javascript-closures-66feb44f6a44 闭包是JavaScript中一个基 ...
- 变位词(0029)-swustoj
变位词(0029)水题 变位词如果两个单词的组成字母完全相同,只是字母的排列顺序不一样,则它们就是变位词,两个单词相同也被认为是变位词.如tea 与eat , nic 与cin, ddc与dcd, a ...
- java基础回顾(2)
java中只有两种类型:基础类型.引用类型 8中基本类型:byte short int long float double char boolean,其中byte类型取值范围[-2^7~2^7-1] ...
- django-Ajax发送POST请求(csrf跨站请求的三种方式),文件的上传
第一种 <script> $(".eq").on("click",function () { $.ajax({ url:"/eq/&quo ...
- 03.redis与ssm整合(mybatis二级缓存)
SSM+redis整合 ssm框架之前已经搭建过了,这里不再做代码复制工作. 这里主要是利用redis去做mybatis的二级缓存,mybaits映射文件中所有的select都会刷新已有缓存,如果不存 ...
- 最短路洛谷P2384
题目背景 狗哥做烂了最短路,突然机智的考了Bosh一道,没想到把Bosh考住了...你能帮Bosh解决吗? 他会给你100000000000000000000000000000000000%10金币w ...
- 关于ftp的学习:ftp很多人都会用。但会用,不代表我们真正了解它。
ftp.sftp.ftps,您是否是也跟我一样搞不清楚他们的真正意义.它们之间有关联吗(究竟是何种关联),有区别吗(区别倒地在哪里). 亦或是以为自己知道它们,可我们真的了解并认识它们了吗? 如果您被 ...