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的学习笔记,其中也会掺杂一些学习心得.话不多说,先从基础 ...
随机推荐
- 《天书夜读:从汇编语言到windows内核编程》十 线程与事件
1)驱动中使用到的线程是系统线程,在system进程中.创建线程API函数:PsCreateSystemThread:结束线程(线程内自行调用)API函数:PsTerminateSystemThrea ...
- python基础(三)----字符编码以及文件处理
字符编码与文件处理 一.字符编码 由字符翻译成二进制数字的过程 字符--------(翻译过程)------->数字 这个过程实际就是一个字符如何对应一个特定数字的标准,这个标准称之 ...
- [转]如何监测谁用了SQL Server的Tempdb空间
Tempdb 系统数据库是一个全局资源,供连接到 SQL Server 实例的所有用户使用.在现在的SQL Server里,其使用频率可能会超过用户的想象.如果Tempdb空间耗尽,许多操作将不能完成 ...
- C#中RichEdit控件,保存文本和图片到mysql数据库
分别通过内存流和RTF文件保存 方法1: //建立内存流 MemoryStream ms = new MemoryStream(); //ms.Position = 0; //把当前的richtext ...
- unique & lower_bound C++
原来C++也有unique和lower_bound,只需头文件iostream unique unique可以对数组进行相邻元素的"去重",实现效果是把所有不重复的元素按顺序放在数 ...
- Spring4 IOC详解
Spring4 IOC详解 上一章对Spring做一个快速入门的教程,其中只是简单的提到了IOC的特性.本章便对Spring的IOC进行一个详解.主要从三个方面开始:基于xml文件的Bean配置,基于 ...
- 关于回调(callback)
如果要理解回调,需要在分同步通信.异步通信的基础上了解 举个通俗的例子: 你打电话问书店老板有没有<JS>这本书,如果是同步通信机制,书店老板会说,你稍等,"我查一下" ...
- NGUI_01
序言:这是张三疯第一次开始NGUI插件的学习,刚开始学习,肯定有很多漏洞,后期会及时的补上的.希望大家可以见谅,希望大佬多多指教. 扩充:为提供和我一样的小白找不到免费的NGUI插件,这里分享百度网盘 ...
- javascript权威指南pdf
链接:https://pan.baidu.com/s/1c19qfSk 密码:j4f3
- 河南省第八届ACM省赛---引水工程
引水工程 时间限制:2000 ms | 内存限制:65535 KB 难度: 描述 南水北调工程是优化水资源配置.促进区域协调发展的基础性工程,是新中国成立以来投资额最大.涉及面最广的战略性工程,事 ...